diff --git a/.release-please-individual-manifest.json b/.release-please-individual-manifest.json index 999d31cc830d..7c111b97259c 100644 --- a/.release-please-individual-manifest.json +++ b/.release-please-individual-manifest.json @@ -1,6 +1,7 @@ { - "packages/google-cloud-workloadidentity": "0.1.0", + "packages/google-cloud-biglake-hive": "0.3.2", "packages/google-cloud-ftp": "0.1.0", + "packages/google-cloud-workloadidentity": "0.1.0", "packages/google-crc32c": "1.8.0", "preview-packages/google-cloud-compute": "1.51.0-preview.1" -} +} \ No newline at end of file diff --git a/librarian.yaml b/librarian.yaml index c4715406c1f2..46efa12c79c4 100644 --- a/librarian.yaml +++ b/librarian.yaml @@ -554,6 +554,7 @@ libraries: - name: google-cloud-biglake-hive version: 0.3.2 apis: + - path: google/cloud/biglake/hive/v1 - path: google/cloud/biglake/hive/v1beta python: default_version: v1beta diff --git a/packages/google-cloud-biglake-hive/docs/biglake_hive_v1/hive_metastore_service.rst b/packages/google-cloud-biglake-hive/docs/biglake_hive_v1/hive_metastore_service.rst new file mode 100644 index 000000000000..c168bee93c41 --- /dev/null +++ b/packages/google-cloud-biglake-hive/docs/biglake_hive_v1/hive_metastore_service.rst @@ -0,0 +1,10 @@ +HiveMetastoreService +-------------------------------------- + +.. automodule:: google.cloud.biglake_hive_v1.services.hive_metastore_service + :members: + :inherited-members: + +.. automodule:: google.cloud.biglake_hive_v1.services.hive_metastore_service.pagers + :members: + :inherited-members: diff --git a/packages/google-cloud-biglake-hive/docs/biglake_hive_v1/services_.rst b/packages/google-cloud-biglake-hive/docs/biglake_hive_v1/services_.rst new file mode 100644 index 000000000000..daf0801e56c0 --- /dev/null +++ b/packages/google-cloud-biglake-hive/docs/biglake_hive_v1/services_.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Biglake Hive v1 API +============================================= +.. toctree:: + :maxdepth: 2 + + hive_metastore_service diff --git a/packages/google-cloud-biglake-hive/docs/biglake_hive_v1/types_.rst b/packages/google-cloud-biglake-hive/docs/biglake_hive_v1/types_.rst new file mode 100644 index 000000000000..fce5724ea181 --- /dev/null +++ b/packages/google-cloud-biglake-hive/docs/biglake_hive_v1/types_.rst @@ -0,0 +1,6 @@ +Types for Google Cloud Biglake Hive v1 API +========================================== + +.. automodule:: google.cloud.biglake_hive_v1.types + :members: + :show-inheritance: diff --git a/packages/google-cloud-biglake-hive/docs/index.rst b/packages/google-cloud-biglake-hive/docs/index.rst index 9cc5d27a7448..081dea9b4a7d 100644 --- a/packages/google-cloud-biglake-hive/docs/index.rst +++ b/packages/google-cloud-biglake-hive/docs/index.rst @@ -2,6 +2,9 @@ .. include:: multiprocessing.rst +This package includes clients for multiple versions of Lakehouse. +By default, you will get version ``biglake_hive_v1beta``. + API Reference ------------- @@ -11,6 +14,14 @@ API Reference biglake_hive_v1beta/services_ biglake_hive_v1beta/types_ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + biglake_hive_v1/services_ + biglake_hive_v1/types_ + Changelog --------- diff --git a/packages/google-cloud-biglake-hive/google/cloud/biglake_hive_v1/__init__.py b/packages/google-cloud-biglake-hive/google/cloud/biglake_hive_v1/__init__.py new file mode 100644 index 000000000000..01ff65e7ac7d --- /dev/null +++ b/packages/google-cloud-biglake-hive/google/cloud/biglake_hive_v1/__init__.py @@ -0,0 +1,205 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 sys + +import google.api_core as api_core + +from google.cloud.biglake_hive_v1 import gapic_version as package_version + +__version__ = package_version.__version__ + +from importlib import metadata + +# PEP 0810: Explicit Lazy Imports +# Python 3.15+ natively intercepts and defers these imports. +# Developers can disable this behavior and force eager imports. +# For more information, see: +# https://docs.python.org/3.15/library/sys.html#sys.set_lazy_imports_filter +# Older Python versions safely ignore this variable. +__lazy_modules__ = { + "google.cloud.biglake_hive_v1.services.hive_metastore_service", + "google.cloud.biglake_hive_v1.types.hive_metastore", +} + + +from .services.hive_metastore_service import ( + HiveMetastoreServiceAsyncClient, + HiveMetastoreServiceClient, +) +from .types.hive_metastore import ( + BatchCreatePartitionsRequest, + BatchCreatePartitionsResponse, + BatchDeletePartitionsRequest, + BatchUpdatePartitionsRequest, + BatchUpdatePartitionsResponse, + CreateHiveCatalogRequest, + CreateHiveDatabaseRequest, + CreateHiveTableRequest, + CreatePartitionRequest, + DeleteHiveCatalogRequest, + DeleteHiveDatabaseRequest, + DeleteHiveTableRequest, + FailoverHiveCatalogRequest, + FailoverHiveCatalogResponse, + FieldSchema, + GetHiveCatalogRequest, + GetHiveDatabaseRequest, + GetHiveTableRequest, + HiveCatalog, + HiveDatabase, + HiveTable, + ListHiveCatalogsRequest, + ListHiveCatalogsResponse, + ListHiveDatabasesRequest, + ListHiveDatabasesResponse, + ListHiveTablesRequest, + ListHiveTablesResponse, + ListPartitionsRequest, + ListPartitionsResponse, + Partition, + PartitionValues, + SerdeInfo, + StorageDescriptor, + UpdateHiveCatalogRequest, + UpdateHiveDatabaseRequest, + UpdateHiveTableRequest, + UpdatePartitionRequest, +) + +if hasattr(api_core, "check_python_version") and hasattr( + api_core, "check_dependency_versions" +): # pragma: NO COVER + api_core.check_python_version("google.cloud.biglake_hive_v1") # type: ignore + api_core.check_dependency_versions("google.cloud.biglake_hive_v1") # type: ignore +else: # pragma: NO COVER + # An older version of api_core is installed which does not define the + # functions above. We do equivalent checks manually. + try: + import warnings + + _py_version_str = sys.version.split()[0] + _package_label = "google.cloud.biglake_hive_v1" + if sys.version_info < (3, 10): + warnings.warn( + "You are using a non-supported Python version " + + f"({_py_version_str}). Google will not post any further " + + f"updates to {_package_label} supporting this Python version. " + + "Please upgrade to the latest Python version, or at " + + f"least to Python 3.10, and then update {_package_label}.", + FutureWarning, + ) + + def parse_version_to_tuple(version_string: str): + """Safely converts a semantic version string to a comparable tuple of integers. + Example: "6.33.5" -> (6, 33, 5) + Ignores non-numeric parts and handles common version formats. + Args: + version_string: Version string in the format "x.y.z" or "x.y.z" + Returns: + Tuple of integers for the parsed version string. + """ + parts = [] + for part in version_string.split("."): + try: + parts.append(int(part)) + except ValueError: + # If it's a non-numeric part (e.g., '1.0.0b1' -> 'b1'), stop here. + # This is a simplification compared to 'packaging.parse_version', but sufficient + # for comparing strictly numeric semantic versions. + break + return tuple(parts) + + def _get_version(dependency_name): + try: + version_string: str = metadata.version(dependency_name) + parsed_version = parse_version_to_tuple(version_string) + return (parsed_version, version_string) + except Exception: + # Catch exceptions from metadata.version() (e.g., PackageNotFoundError) + # or errors during parse_version_to_tuple + return (None, "--") + + _dependency_package = "google.protobuf" + _next_supported_version = "6.33.5" + _next_supported_version_tuple = (6, 33, 5) + _recommendation = " (we recommend 7.x)" + (_version_used, _version_used_string) = _get_version(_dependency_package) + if _version_used and _version_used < _next_supported_version_tuple: + warnings.warn( + f"Package {_package_label} depends on " + + f"{_dependency_package}, currently installed at version " + + f"{_version_used_string}. Future updates to " + + f"{_package_label} will require {_dependency_package} at " + + f"version {_next_supported_version} or higher{_recommendation}." + + " Please ensure " + + "that either (a) your Python environment doesn't pin the " + + f"version of {_dependency_package}, so that updates to " + + f"{_package_label} can require the higher version, or " + + "(b) you manually update your Python environment to use at " + + f"least version {_next_supported_version} of " + + f"{_dependency_package}.", + FutureWarning, + ) + except Exception: + warnings.warn( + "Could not determine the version of Python " + + "currently being used. To continue receiving " + + "updates for {_package_label}, ensure you are " + + "using a supported version of Python; see " + + "https://devguide.python.org/versions/" + ) + +__all__ = ( + "HiveMetastoreServiceAsyncClient", + "BatchCreatePartitionsRequest", + "BatchCreatePartitionsResponse", + "BatchDeletePartitionsRequest", + "BatchUpdatePartitionsRequest", + "BatchUpdatePartitionsResponse", + "CreateHiveCatalogRequest", + "CreateHiveDatabaseRequest", + "CreateHiveTableRequest", + "CreatePartitionRequest", + "DeleteHiveCatalogRequest", + "DeleteHiveDatabaseRequest", + "DeleteHiveTableRequest", + "FailoverHiveCatalogRequest", + "FailoverHiveCatalogResponse", + "FieldSchema", + "GetHiveCatalogRequest", + "GetHiveDatabaseRequest", + "GetHiveTableRequest", + "HiveCatalog", + "HiveDatabase", + "HiveMetastoreServiceClient", + "HiveTable", + "ListHiveCatalogsRequest", + "ListHiveCatalogsResponse", + "ListHiveDatabasesRequest", + "ListHiveDatabasesResponse", + "ListHiveTablesRequest", + "ListHiveTablesResponse", + "ListPartitionsRequest", + "ListPartitionsResponse", + "Partition", + "PartitionValues", + "SerdeInfo", + "StorageDescriptor", + "UpdateHiveCatalogRequest", + "UpdateHiveDatabaseRequest", + "UpdateHiveTableRequest", + "UpdatePartitionRequest", +) diff --git a/packages/google-cloud-biglake-hive/google/cloud/biglake_hive_v1/gapic_metadata.json b/packages/google-cloud-biglake-hive/google/cloud/biglake_hive_v1/gapic_metadata.json new file mode 100644 index 000000000000..1dac6b7d9f16 --- /dev/null +++ b/packages/google-cloud-biglake-hive/google/cloud/biglake_hive_v1/gapic_metadata.json @@ -0,0 +1,328 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.biglake_hive_v1", + "protoPackage": "google.cloud.biglake.hive.v1", + "schema": "1.0", + "services": { + "HiveMetastoreService": { + "clients": { + "grpc": { + "libraryClient": "HiveMetastoreServiceClient", + "rpcs": { + "BatchCreatePartitions": { + "methods": [ + "batch_create_partitions" + ] + }, + "BatchDeletePartitions": { + "methods": [ + "batch_delete_partitions" + ] + }, + "BatchUpdatePartitions": { + "methods": [ + "batch_update_partitions" + ] + }, + "CreateHiveCatalog": { + "methods": [ + "create_hive_catalog" + ] + }, + "CreateHiveDatabase": { + "methods": [ + "create_hive_database" + ] + }, + "CreateHiveTable": { + "methods": [ + "create_hive_table" + ] + }, + "DeleteHiveCatalog": { + "methods": [ + "delete_hive_catalog" + ] + }, + "DeleteHiveDatabase": { + "methods": [ + "delete_hive_database" + ] + }, + "DeleteHiveTable": { + "methods": [ + "delete_hive_table" + ] + }, + "FailoverHiveCatalog": { + "methods": [ + "failover_hive_catalog" + ] + }, + "GetHiveCatalog": { + "methods": [ + "get_hive_catalog" + ] + }, + "GetHiveDatabase": { + "methods": [ + "get_hive_database" + ] + }, + "GetHiveTable": { + "methods": [ + "get_hive_table" + ] + }, + "ListHiveCatalogs": { + "methods": [ + "list_hive_catalogs" + ] + }, + "ListHiveDatabases": { + "methods": [ + "list_hive_databases" + ] + }, + "ListHiveTables": { + "methods": [ + "list_hive_tables" + ] + }, + "ListPartitions": { + "methods": [ + "list_partitions" + ] + }, + "UpdateHiveCatalog": { + "methods": [ + "update_hive_catalog" + ] + }, + "UpdateHiveDatabase": { + "methods": [ + "update_hive_database" + ] + }, + "UpdateHiveTable": { + "methods": [ + "update_hive_table" + ] + } + } + }, + "grpc-async": { + "libraryClient": "HiveMetastoreServiceAsyncClient", + "rpcs": { + "BatchCreatePartitions": { + "methods": [ + "batch_create_partitions" + ] + }, + "BatchDeletePartitions": { + "methods": [ + "batch_delete_partitions" + ] + }, + "BatchUpdatePartitions": { + "methods": [ + "batch_update_partitions" + ] + }, + "CreateHiveCatalog": { + "methods": [ + "create_hive_catalog" + ] + }, + "CreateHiveDatabase": { + "methods": [ + "create_hive_database" + ] + }, + "CreateHiveTable": { + "methods": [ + "create_hive_table" + ] + }, + "DeleteHiveCatalog": { + "methods": [ + "delete_hive_catalog" + ] + }, + "DeleteHiveDatabase": { + "methods": [ + "delete_hive_database" + ] + }, + "DeleteHiveTable": { + "methods": [ + "delete_hive_table" + ] + }, + "FailoverHiveCatalog": { + "methods": [ + "failover_hive_catalog" + ] + }, + "GetHiveCatalog": { + "methods": [ + "get_hive_catalog" + ] + }, + "GetHiveDatabase": { + "methods": [ + "get_hive_database" + ] + }, + "GetHiveTable": { + "methods": [ + "get_hive_table" + ] + }, + "ListHiveCatalogs": { + "methods": [ + "list_hive_catalogs" + ] + }, + "ListHiveDatabases": { + "methods": [ + "list_hive_databases" + ] + }, + "ListHiveTables": { + "methods": [ + "list_hive_tables" + ] + }, + "ListPartitions": { + "methods": [ + "list_partitions" + ] + }, + "UpdateHiveCatalog": { + "methods": [ + "update_hive_catalog" + ] + }, + "UpdateHiveDatabase": { + "methods": [ + "update_hive_database" + ] + }, + "UpdateHiveTable": { + "methods": [ + "update_hive_table" + ] + } + } + }, + "rest": { + "libraryClient": "HiveMetastoreServiceClient", + "rpcs": { + "BatchCreatePartitions": { + "methods": [ + "batch_create_partitions" + ] + }, + "BatchDeletePartitions": { + "methods": [ + "batch_delete_partitions" + ] + }, + "BatchUpdatePartitions": { + "methods": [ + "batch_update_partitions" + ] + }, + "CreateHiveCatalog": { + "methods": [ + "create_hive_catalog" + ] + }, + "CreateHiveDatabase": { + "methods": [ + "create_hive_database" + ] + }, + "CreateHiveTable": { + "methods": [ + "create_hive_table" + ] + }, + "DeleteHiveCatalog": { + "methods": [ + "delete_hive_catalog" + ] + }, + "DeleteHiveDatabase": { + "methods": [ + "delete_hive_database" + ] + }, + "DeleteHiveTable": { + "methods": [ + "delete_hive_table" + ] + }, + "FailoverHiveCatalog": { + "methods": [ + "failover_hive_catalog" + ] + }, + "GetHiveCatalog": { + "methods": [ + "get_hive_catalog" + ] + }, + "GetHiveDatabase": { + "methods": [ + "get_hive_database" + ] + }, + "GetHiveTable": { + "methods": [ + "get_hive_table" + ] + }, + "ListHiveCatalogs": { + "methods": [ + "list_hive_catalogs" + ] + }, + "ListHiveDatabases": { + "methods": [ + "list_hive_databases" + ] + }, + "ListHiveTables": { + "methods": [ + "list_hive_tables" + ] + }, + "ListPartitions": { + "methods": [ + "list_partitions" + ] + }, + "UpdateHiveCatalog": { + "methods": [ + "update_hive_catalog" + ] + }, + "UpdateHiveDatabase": { + "methods": [ + "update_hive_database" + ] + }, + "UpdateHiveTable": { + "methods": [ + "update_hive_table" + ] + } + } + } + } + } + } +} diff --git a/packages/google-cloud-biglake-hive/google/cloud/biglake_hive_v1/gapic_version.py b/packages/google-cloud-biglake-hive/google/cloud/biglake_hive_v1/gapic_version.py new file mode 100644 index 000000000000..6fbb3bd7429b --- /dev/null +++ b/packages/google-cloud-biglake-hive/google/cloud/biglake_hive_v1/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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. +# +__version__ = "0.3.2" # {x-release-please-version} diff --git a/packages/google-cloud-biglake-hive/google/cloud/biglake_hive_v1/py.typed b/packages/google-cloud-biglake-hive/google/cloud/biglake_hive_v1/py.typed new file mode 100644 index 000000000000..19c7b06e6f33 --- /dev/null +++ b/packages/google-cloud-biglake-hive/google/cloud/biglake_hive_v1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-biglake-hive package uses inline types. diff --git a/packages/google-cloud-biglake-hive/google/cloud/biglake_hive_v1/services/__init__.py b/packages/google-cloud-biglake-hive/google/cloud/biglake_hive_v1/services/__init__.py new file mode 100644 index 000000000000..32b36c5c4fe0 --- /dev/null +++ b/packages/google-cloud-biglake-hive/google/cloud/biglake_hive_v1/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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. +# diff --git a/packages/google-cloud-biglake-hive/google/cloud/biglake_hive_v1/services/hive_metastore_service/__init__.py b/packages/google-cloud-biglake-hive/google/cloud/biglake_hive_v1/services/hive_metastore_service/__init__.py new file mode 100644 index 000000000000..53657ac45505 --- /dev/null +++ b/packages/google-cloud-biglake-hive/google/cloud/biglake_hive_v1/services/hive_metastore_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 .async_client import HiveMetastoreServiceAsyncClient +from .client import HiveMetastoreServiceClient + +__all__ = ( + "HiveMetastoreServiceClient", + "HiveMetastoreServiceAsyncClient", +) diff --git a/packages/google-cloud-biglake-hive/google/cloud/biglake_hive_v1/services/hive_metastore_service/async_client.py b/packages/google-cloud-biglake-hive/google/cloud/biglake_hive_v1/services/hive_metastore_service/async_client.py new file mode 100644 index 000000000000..99672b58027a --- /dev/null +++ b/packages/google-cloud-biglake-hive/google/cloud/biglake_hive_v1/services/hive_metastore_service/async_client.py @@ -0,0 +1,2781 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 logging as std_logging +import re +from collections import OrderedDict +from typing import ( + AsyncIterable, + Awaitable, + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) + +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.api_core.client_options import ClientOptions +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.biglake_hive_v1 import gapic_version as package_version + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore + +from google.cloud.biglake_hive_v1.services.hive_metastore_service import pagers +from google.cloud.biglake_hive_v1.types import hive_metastore + +from .client import HiveMetastoreServiceClient +from .transports.base import DEFAULT_CLIENT_INFO, HiveMetastoreServiceTransport +from .transports.grpc_asyncio import HiveMetastoreServiceGrpcAsyncIOTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class HiveMetastoreServiceAsyncClient: + """Hive Metastore Service is a biglake service that allows users to + manage their external Hive catalogs. Full API compatibility with OSS + Hive Metastore APIs is not supported. The methods match the Hive + Metastore API spec mostly except for a few exceptions. These include + listing resources with pattern, environment context which are + combined in a single List API, return of ListResponse object instead + of a list of resources, transactions, locks, etc. + + The BigLake Hive Metastore API defines the following resources: + + - A collection of Google Cloud projects: ``/projects/*`` + - Each project has a collection of catalogs: ``/catalogs/*`` + - Each catalog has a collection of databases: ``/databases/*`` + - Each database has a collection of tables: ``/tables/*`` + """ + + _client: HiveMetastoreServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = HiveMetastoreServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = HiveMetastoreServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = HiveMetastoreServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = HiveMetastoreServiceClient._DEFAULT_UNIVERSE + + catalog_path = staticmethod(HiveMetastoreServiceClient.catalog_path) + parse_catalog_path = staticmethod(HiveMetastoreServiceClient.parse_catalog_path) + namespace_path = staticmethod(HiveMetastoreServiceClient.namespace_path) + parse_namespace_path = staticmethod(HiveMetastoreServiceClient.parse_namespace_path) + table_path = staticmethod(HiveMetastoreServiceClient.table_path) + parse_table_path = staticmethod(HiveMetastoreServiceClient.parse_table_path) + common_billing_account_path = staticmethod( + HiveMetastoreServiceClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + HiveMetastoreServiceClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod(HiveMetastoreServiceClient.common_folder_path) + parse_common_folder_path = staticmethod( + HiveMetastoreServiceClient.parse_common_folder_path + ) + common_organization_path = staticmethod( + HiveMetastoreServiceClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + HiveMetastoreServiceClient.parse_common_organization_path + ) + common_project_path = staticmethod(HiveMetastoreServiceClient.common_project_path) + parse_common_project_path = staticmethod( + HiveMetastoreServiceClient.parse_common_project_path + ) + common_location_path = staticmethod(HiveMetastoreServiceClient.common_location_path) + parse_common_location_path = staticmethod( + HiveMetastoreServiceClient.parse_common_location_path + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + HiveMetastoreServiceAsyncClient: The constructed client. + """ + sa_info_func = ( + HiveMetastoreServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(HiveMetastoreServiceAsyncClient, info, *args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + HiveMetastoreServiceAsyncClient: The constructed client. + """ + sa_file_func = ( + HiveMetastoreServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func(HiveMetastoreServiceAsyncClient, filename, *args, **kwargs) + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[ClientOptions] = None + ): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return HiveMetastoreServiceClient.get_mtls_endpoint_and_cert_source( + client_options + ) # type: ignore + + @property + def transport(self) -> HiveMetastoreServiceTransport: + """Returns the transport used by the client instance. + + Returns: + HiveMetastoreServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self) -> str: + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = HiveMetastoreServiceClient.get_transport_class + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[ + str, + HiveMetastoreServiceTransport, + Callable[..., HiveMetastoreServiceTransport], + ] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the hive metastore service async client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,HiveMetastoreServiceTransport,Callable[..., HiveMetastoreServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport to use. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the HiveMetastoreServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = HiveMetastoreServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.cloud.biglake.hive_v1.HiveMetastoreServiceAsyncClient`.", + extra={ + "serviceName": "google.cloud.biglake.hive.v1.HiveMetastoreService", + "universeDomain": getattr( + self._client._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._client._transport, "_credentials") + else { + "serviceName": "google.cloud.biglake.hive.v1.HiveMetastoreService", + "credentialsType": None, + }, + ) + + async def create_hive_catalog( + self, + request: Optional[Union[hive_metastore.CreateHiveCatalogRequest, dict]] = None, + *, + parent: Optional[str] = None, + hive_catalog: Optional[hive_metastore.HiveCatalog] = None, + hive_catalog_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> hive_metastore.HiveCatalog: + r"""Creates a new hive catalog. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import biglake_hive_v1 + + async def sample_create_hive_catalog(): + # Create a client + client = biglake_hive_v1.HiveMetastoreServiceAsyncClient() + + # Initialize request argument(s) + hive_catalog = biglake_hive_v1.HiveCatalog() + hive_catalog.location_uri = "location_uri_value" + + request = biglake_hive_v1.CreateHiveCatalogRequest( + parent="parent_value", + hive_catalog=hive_catalog, + hive_catalog_id="hive_catalog_id_value", + primary_location="primary_location_value", + ) + + # Make the request + response = await client.create_hive_catalog(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.biglake_hive_v1.types.CreateHiveCatalogRequest, dict]]): + The request object. Request message for the + CreateHiveCatalog method. + parent (:class:`str`): + Required. The parent resource where this catalog will be + created. Format: projects/{project_id_or_number} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + hive_catalog (:class:`google.cloud.biglake_hive_v1.types.HiveCatalog`): + Required. The catalog to create. The ``name`` field does + not need to be provided. Gets copied over from + catalog_id. + + This corresponds to the ``hive_catalog`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + hive_catalog_id (:class:`str`): + Required. The Hive Catalog ID to use + for the catalog that will become the + final component of the catalog's + resource name. The maximum length is 256 + characters. + + This corresponds to the ``hive_catalog_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.biglake_hive_v1.types.HiveCatalog: + The HiveCatalog contains spark/hive + databases and tables in the BigLake + Metastore. While creating resources + under a catalog, ideally ensure that the + storage bucket location, spark / hive + engine location or any other compute + location match. Catalog can be viewed + as the destination for migrating an + on-prem Hive metastore to GCP. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, hive_catalog, hive_catalog_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, hive_metastore.CreateHiveCatalogRequest): + request = hive_metastore.CreateHiveCatalogRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if hive_catalog is not None: + request.hive_catalog = hive_catalog + if hive_catalog_id is not None: + request.hive_catalog_id = hive_catalog_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_hive_catalog + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_hive_catalog( + self, + request: Optional[Union[hive_metastore.GetHiveCatalogRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> hive_metastore.HiveCatalog: + r"""Gets the catalog specified by the resource name. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import biglake_hive_v1 + + async def sample_get_hive_catalog(): + # Create a client + client = biglake_hive_v1.HiveMetastoreServiceAsyncClient() + + # Initialize request argument(s) + request = biglake_hive_v1.GetHiveCatalogRequest( + name="name_value", + ) + + # Make the request + response = await client.get_hive_catalog(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.biglake_hive_v1.types.GetHiveCatalogRequest, dict]]): + The request object. Request message for the + GetHiveCatalog method. + name (:class:`str`): + Required. The name of the catalog to retrieve. Format: + projects/{project_id_or_number}/catalogs/{catalog_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.biglake_hive_v1.types.HiveCatalog: + The HiveCatalog contains spark/hive + databases and tables in the BigLake + Metastore. While creating resources + under a catalog, ideally ensure that the + storage bucket location, spark / hive + engine location or any other compute + location match. Catalog can be viewed + as the destination for migrating an + on-prem Hive metastore to GCP. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, hive_metastore.GetHiveCatalogRequest): + request = hive_metastore.GetHiveCatalogRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_hive_catalog + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_hive_catalogs( + self, + request: Optional[Union[hive_metastore.ListHiveCatalogsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListHiveCatalogsAsyncPager: + r"""List all catalogs in a specified project. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import biglake_hive_v1 + + async def sample_list_hive_catalogs(): + # Create a client + client = biglake_hive_v1.HiveMetastoreServiceAsyncClient() + + # Initialize request argument(s) + request = biglake_hive_v1.ListHiveCatalogsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_hive_catalogs(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.biglake_hive_v1.types.ListHiveCatalogsRequest, dict]]): + The request object. Request message for the + ListHiveCatalogs method. + parent (:class:`str`): + Required. The project to list catalogs from. Format: + projects/{project_id_or_number} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.biglake_hive_v1.services.hive_metastore_service.pagers.ListHiveCatalogsAsyncPager: + Response message for the + ListHiveCatalogs method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, hive_metastore.ListHiveCatalogsRequest): + request = hive_metastore.ListHiveCatalogsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_hive_catalogs + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListHiveCatalogsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_hive_catalog( + self, + request: Optional[Union[hive_metastore.UpdateHiveCatalogRequest, dict]] = None, + *, + hive_catalog: Optional[hive_metastore.HiveCatalog] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> hive_metastore.HiveCatalog: + r"""Updates an existing catalog. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import biglake_hive_v1 + + async def sample_update_hive_catalog(): + # Create a client + client = biglake_hive_v1.HiveMetastoreServiceAsyncClient() + + # Initialize request argument(s) + hive_catalog = biglake_hive_v1.HiveCatalog() + hive_catalog.location_uri = "location_uri_value" + + request = biglake_hive_v1.UpdateHiveCatalogRequest( + hive_catalog=hive_catalog, + ) + + # Make the request + response = await client.update_hive_catalog(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.biglake_hive_v1.types.UpdateHiveCatalogRequest, dict]]): + The request object. Request message for the + UpdateHiveCatalog method. + hive_catalog (:class:`google.cloud.biglake_hive_v1.types.HiveCatalog`): + Required. The hive catalog to update. The name under the + catalog is used to identify the catalog. Format: + projects/{project_id_or_number}/catalogs/{catalog_id} + + This corresponds to the ``hive_catalog`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. The list of fields to update. + + For the ``FieldMask`` definition, see + https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask + If not set, defaults to all of the fields that are + allowed to update. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.biglake_hive_v1.types.HiveCatalog: + The HiveCatalog contains spark/hive + databases and tables in the BigLake + Metastore. While creating resources + under a catalog, ideally ensure that the + storage bucket location, spark / hive + engine location or any other compute + location match. Catalog can be viewed + as the destination for migrating an + on-prem Hive metastore to GCP. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [hive_catalog, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, hive_metastore.UpdateHiveCatalogRequest): + request = hive_metastore.UpdateHiveCatalogRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if hive_catalog is not None: + request.hive_catalog = hive_catalog + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_hive_catalog + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("hive_catalog.name", request.hive_catalog.name),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_hive_catalog( + self, + request: Optional[Union[hive_metastore.DeleteHiveCatalogRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes an existing catalog specified by the catalog + ID. Delete will fail if the catalog is not empty. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import biglake_hive_v1 + + async def sample_delete_hive_catalog(): + # Create a client + client = biglake_hive_v1.HiveMetastoreServiceAsyncClient() + + # Initialize request argument(s) + request = biglake_hive_v1.DeleteHiveCatalogRequest( + name="name_value", + ) + + # Make the request + await client.delete_hive_catalog(request=request) + + Args: + request (Optional[Union[google.cloud.biglake_hive_v1.types.DeleteHiveCatalogRequest, dict]]): + The request object. Request message for the + DeleteHiveCatalog method. + name (:class:`str`): + Required. The name of the catalog to delete. Format: + projects/{project_id_or_number}/catalogs/{catalog_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, hive_metastore.DeleteHiveCatalogRequest): + request = hive_metastore.DeleteHiveCatalogRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_hive_catalog + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def create_hive_database( + self, + request: Optional[Union[hive_metastore.CreateHiveDatabaseRequest, dict]] = None, + *, + parent: Optional[str] = None, + hive_database: Optional[hive_metastore.HiveDatabase] = None, + hive_database_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> hive_metastore.HiveDatabase: + r"""Creates a new database. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import biglake_hive_v1 + + async def sample_create_hive_database(): + # Create a client + client = biglake_hive_v1.HiveMetastoreServiceAsyncClient() + + # Initialize request argument(s) + request = biglake_hive_v1.CreateHiveDatabaseRequest( + parent="parent_value", + hive_database_id="hive_database_id_value", + ) + + # Make the request + response = await client.create_hive_database(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.biglake_hive_v1.types.CreateHiveDatabaseRequest, dict]]): + The request object. Request message for the + CreateHiveDatabase method. + parent (:class:`str`): + Required. The parent resource where this database will + be created. Format: + projects/{project_id_or_number}/catalogs/{catalog_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + hive_database (:class:`google.cloud.biglake_hive_v1.types.HiveDatabase`): + Required. The database to create. The ``name`` field + does not need to be provided. + + This corresponds to the ``hive_database`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + hive_database_id (:class:`str`): + Required. The ID to use for the Hive + Database. The maximum length is 128 + characters. + + This corresponds to the ``hive_database_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.biglake_hive_v1.types.HiveDatabase: + Stores the hive database information. + It includes the database name, + description, location and properties + associated with the database. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, hive_database, hive_database_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, hive_metastore.CreateHiveDatabaseRequest): + request = hive_metastore.CreateHiveDatabaseRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if hive_database is not None: + request.hive_database = hive_database + if hive_database_id is not None: + request.hive_database_id = hive_database_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_hive_database + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_hive_database( + self, + request: Optional[Union[hive_metastore.GetHiveDatabaseRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> hive_metastore.HiveDatabase: + r"""Gets the database specified by the resource name. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import biglake_hive_v1 + + async def sample_get_hive_database(): + # Create a client + client = biglake_hive_v1.HiveMetastoreServiceAsyncClient() + + # Initialize request argument(s) + request = biglake_hive_v1.GetHiveDatabaseRequest( + name="name_value", + ) + + # Make the request + response = await client.get_hive_database(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.biglake_hive_v1.types.GetHiveDatabaseRequest, dict]]): + The request object. Request message for the + GetHiveDatabase method. + name (:class:`str`): + Required. The name of the database to retrieve. Format: + projects/{project_id_or_number}/catalogs/{catalog_id}/databases/{database_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.biglake_hive_v1.types.HiveDatabase: + Stores the hive database information. + It includes the database name, + description, location and properties + associated with the database. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, hive_metastore.GetHiveDatabaseRequest): + request = hive_metastore.GetHiveDatabaseRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_hive_database + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_hive_databases( + self, + request: Optional[Union[hive_metastore.ListHiveDatabasesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListHiveDatabasesAsyncPager: + r"""List all databases in a specified catalog. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import biglake_hive_v1 + + async def sample_list_hive_databases(): + # Create a client + client = biglake_hive_v1.HiveMetastoreServiceAsyncClient() + + # Initialize request argument(s) + request = biglake_hive_v1.ListHiveDatabasesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_hive_databases(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.biglake_hive_v1.types.ListHiveDatabasesRequest, dict]]): + The request object. Request message for the + ListHiveDatabases method. + parent (:class:`str`): + Required. The hive catalog to list databases from. + Format: + projects/{project_id_or_number}/catalogs/{catalog_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.biglake_hive_v1.services.hive_metastore_service.pagers.ListHiveDatabasesAsyncPager: + Response message for the + ListHiveDatabases method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, hive_metastore.ListHiveDatabasesRequest): + request = hive_metastore.ListHiveDatabasesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_hive_databases + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListHiveDatabasesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_hive_database( + self, + request: Optional[Union[hive_metastore.UpdateHiveDatabaseRequest, dict]] = None, + *, + hive_database: Optional[hive_metastore.HiveDatabase] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> hive_metastore.HiveDatabase: + r"""Updates an existing database specified by the + database name. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import biglake_hive_v1 + + async def sample_update_hive_database(): + # Create a client + client = biglake_hive_v1.HiveMetastoreServiceAsyncClient() + + # Initialize request argument(s) + request = biglake_hive_v1.UpdateHiveDatabaseRequest( + ) + + # Make the request + response = await client.update_hive_database(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.biglake_hive_v1.types.UpdateHiveDatabaseRequest, dict]]): + The request object. Request message for the + UpdateHiveDatabase method. + hive_database (:class:`google.cloud.biglake_hive_v1.types.HiveDatabase`): + Required. The database to update. + + The database's ``name`` field is used to identify the + database to update. Format: + projects/{project_id_or_number}/catalogs/{catalog_id}/databases/{database_id} + + This corresponds to the ``hive_database`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. The list of fields to + update. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.biglake_hive_v1.types.HiveDatabase: + Stores the hive database information. + It includes the database name, + description, location and properties + associated with the database. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [hive_database, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, hive_metastore.UpdateHiveDatabaseRequest): + request = hive_metastore.UpdateHiveDatabaseRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if hive_database is not None: + request.hive_database = hive_database + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_hive_database + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("hive_database.name", request.hive_database.name),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_hive_database( + self, + request: Optional[Union[hive_metastore.DeleteHiveDatabaseRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes an existing database specified by the + database name. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import biglake_hive_v1 + + async def sample_delete_hive_database(): + # Create a client + client = biglake_hive_v1.HiveMetastoreServiceAsyncClient() + + # Initialize request argument(s) + request = biglake_hive_v1.DeleteHiveDatabaseRequest( + name="name_value", + ) + + # Make the request + await client.delete_hive_database(request=request) + + Args: + request (Optional[Union[google.cloud.biglake_hive_v1.types.DeleteHiveDatabaseRequest, dict]]): + The request object. Request message for the + DeleteHiveDatabase method. + name (:class:`str`): + Required. The name of the database to delete. Format: + projects/{project_id_or_number}/catalogs/{catalog_id}/databases/{database_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, hive_metastore.DeleteHiveDatabaseRequest): + request = hive_metastore.DeleteHiveDatabaseRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_hive_database + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def create_hive_table( + self, + request: Optional[Union[hive_metastore.CreateHiveTableRequest, dict]] = None, + *, + parent: Optional[str] = None, + hive_table: Optional[hive_metastore.HiveTable] = None, + hive_table_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> hive_metastore.HiveTable: + r"""Creates a new hive table. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import biglake_hive_v1 + + async def sample_create_hive_table(): + # Create a client + client = biglake_hive_v1.HiveMetastoreServiceAsyncClient() + + # Initialize request argument(s) + hive_table = biglake_hive_v1.HiveTable() + hive_table.storage_descriptor.columns.name = "name_value" + hive_table.storage_descriptor.columns.type_ = "type__value" + + request = biglake_hive_v1.CreateHiveTableRequest( + parent="parent_value", + hive_table=hive_table, + hive_table_id="hive_table_id_value", + ) + + # Make the request + response = await client.create_hive_table(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.biglake_hive_v1.types.CreateHiveTableRequest, dict]]): + The request object. Request message for the + CreateHiveTable method. + parent (:class:`str`): + Required. The parent resource for the table to be + created. Format: + projects/{project_id_or_number}/catalogs/{catalog_id}/databases/{database_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + hive_table (:class:`google.cloud.biglake_hive_v1.types.HiveTable`): + Required. The Hive Table to create. The ``name`` field + does not need to be provided. + + This corresponds to the ``hive_table`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + hive_table_id (:class:`str`): + Required. The Hive Table ID to use + for the table that will become the final + component of the table's resource name. + The maximum length is 256 characters. + + This corresponds to the ``hive_table_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.biglake_hive_v1.types.HiveTable: + Stores the hive table information. It + includes the table name, schema (column + names and types), data location, storage + format, serde info, etc. This message + closely matches the Table object in the + IMetastoreClient + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, hive_table, hive_table_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, hive_metastore.CreateHiveTableRequest): + request = hive_metastore.CreateHiveTableRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if hive_table is not None: + request.hive_table = hive_table + if hive_table_id is not None: + request.hive_table_id = hive_table_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_hive_table + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_hive_table( + self, + request: Optional[Union[hive_metastore.GetHiveTableRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> hive_metastore.HiveTable: + r"""Gets the table specified by the resource name. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import biglake_hive_v1 + + async def sample_get_hive_table(): + # Create a client + client = biglake_hive_v1.HiveMetastoreServiceAsyncClient() + + # Initialize request argument(s) + request = biglake_hive_v1.GetHiveTableRequest( + name="name_value", + ) + + # Make the request + response = await client.get_hive_table(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.biglake_hive_v1.types.GetHiveTableRequest, dict]]): + The request object. Request message for the GetHiveTable + method. + name (:class:`str`): + Required. The name of the table to retrieve. Format: + projects/{project_id_or_number}/catalogs/{catalog_id}/databases/{database_id}/tables/{table_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.biglake_hive_v1.types.HiveTable: + Stores the hive table information. It + includes the table name, schema (column + names and types), data location, storage + format, serde info, etc. This message + closely matches the Table object in the + IMetastoreClient + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, hive_metastore.GetHiveTableRequest): + request = hive_metastore.GetHiveTableRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_hive_table + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_hive_tables( + self, + request: Optional[Union[hive_metastore.ListHiveTablesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListHiveTablesAsyncPager: + r"""List all hive tables in a specified project under the + hive catalog and database. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import biglake_hive_v1 + + async def sample_list_hive_tables(): + # Create a client + client = biglake_hive_v1.HiveMetastoreServiceAsyncClient() + + # Initialize request argument(s) + request = biglake_hive_v1.ListHiveTablesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_hive_tables(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.biglake_hive_v1.types.ListHiveTablesRequest, dict]]): + The request object. Request message for the + ListHiveTables method. + parent (:class:`str`): + Required. The database to list tables from. Format: + projects/{project_id_or_number}/catalogs/{catalog_id}/databases/{database_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.biglake_hive_v1.services.hive_metastore_service.pagers.ListHiveTablesAsyncPager: + Response message for the + ListHiveTables method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, hive_metastore.ListHiveTablesRequest): + request = hive_metastore.ListHiveTablesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_hive_tables + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListHiveTablesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_hive_table( + self, + request: Optional[Union[hive_metastore.UpdateHiveTableRequest, dict]] = None, + *, + hive_table: Optional[hive_metastore.HiveTable] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> hive_metastore.HiveTable: + r"""Updates an existing table specified by the table + name. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import biglake_hive_v1 + + async def sample_update_hive_table(): + # Create a client + client = biglake_hive_v1.HiveMetastoreServiceAsyncClient() + + # Initialize request argument(s) + hive_table = biglake_hive_v1.HiveTable() + hive_table.storage_descriptor.columns.name = "name_value" + hive_table.storage_descriptor.columns.type_ = "type__value" + + request = biglake_hive_v1.UpdateHiveTableRequest( + hive_table=hive_table, + ) + + # Make the request + response = await client.update_hive_table(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.biglake_hive_v1.types.UpdateHiveTableRequest, dict]]): + The request object. Request message for the + UpdateHiveTable method. + hive_table (:class:`google.cloud.biglake_hive_v1.types.HiveTable`): + Required. The table to update. + + The table's ``name`` field is used to identify the table + to update. Format: + projects/{project_id_or_number}/catalogs/{catalog_id}/databases/{database_id}/tables/{table_id} + + This corresponds to the ``hive_table`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. The list of fields to + update. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.biglake_hive_v1.types.HiveTable: + Stores the hive table information. It + includes the table name, schema (column + names and types), data location, storage + format, serde info, etc. This message + closely matches the Table object in the + IMetastoreClient + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [hive_table, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, hive_metastore.UpdateHiveTableRequest): + request = hive_metastore.UpdateHiveTableRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if hive_table is not None: + request.hive_table = hive_table + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_hive_table + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("hive_table.name", request.hive_table.name),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_hive_table( + self, + request: Optional[Union[hive_metastore.DeleteHiveTableRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes an existing table specified by the table + name. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import biglake_hive_v1 + + async def sample_delete_hive_table(): + # Create a client + client = biglake_hive_v1.HiveMetastoreServiceAsyncClient() + + # Initialize request argument(s) + request = biglake_hive_v1.DeleteHiveTableRequest( + name="name_value", + ) + + # Make the request + await client.delete_hive_table(request=request) + + Args: + request (Optional[Union[google.cloud.biglake_hive_v1.types.DeleteHiveTableRequest, dict]]): + The request object. Request message for the + DeleteHiveTable method. + name (:class:`str`): + Required. The name of the database to delete. Format: + projects/{project_id_or_number}/catalogs/{catalog_id}/databases/{database_id}/tables/{table_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, hive_metastore.DeleteHiveTableRequest): + request = hive_metastore.DeleteHiveTableRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_hive_table + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def batch_create_partitions( + self, + request: Optional[ + Union[hive_metastore.BatchCreatePartitionsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> hive_metastore.BatchCreatePartitionsResponse: + r"""Adds partitions to a table. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import biglake_hive_v1 + + async def sample_batch_create_partitions(): + # Create a client + client = biglake_hive_v1.HiveMetastoreServiceAsyncClient() + + # Initialize request argument(s) + requests = biglake_hive_v1.CreatePartitionRequest() + requests.parent = "parent_value" + requests.partition.values = ['values_value1', 'values_value2'] + + request = biglake_hive_v1.BatchCreatePartitionsRequest( + parent="parent_value", + requests=requests, + ) + + # Make the request + response = await client.batch_create_partitions(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.biglake_hive_v1.types.BatchCreatePartitionsRequest, dict]]): + The request object. Request message for the + BatchCreatePartitions method. + parent (:class:`str`): + Required. Reference to the table to + where the partitions to be added, in the + format of + projects/{project}/catalogs/{catalogs}/databases/{database}/tables/{table}. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.biglake_hive_v1.types.BatchCreatePartitionsResponse: + Response message for + BatchCreatePartitions. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, hive_metastore.BatchCreatePartitionsRequest): + request = hive_metastore.BatchCreatePartitionsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.batch_create_partitions + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def batch_delete_partitions( + self, + request: Optional[ + Union[hive_metastore.BatchDeletePartitionsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes partitions from a table. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import biglake_hive_v1 + + async def sample_batch_delete_partitions(): + # Create a client + client = biglake_hive_v1.HiveMetastoreServiceAsyncClient() + + # Initialize request argument(s) + partition_values = biglake_hive_v1.PartitionValues() + partition_values.values = ['values_value1', 'values_value2'] + + request = biglake_hive_v1.BatchDeletePartitionsRequest( + parent="parent_value", + partition_values=partition_values, + ) + + # Make the request + await client.batch_delete_partitions(request=request) + + Args: + request (Optional[Union[google.cloud.biglake_hive_v1.types.BatchDeletePartitionsRequest, dict]]): + The request object. Request message for + BatchDeletePartitions. The Partition is + uniquely identified by values, which is + an ordered list. Hence, there is no + separate name or partition id field. + parent (:class:`str`): + Required. Reference to the table to + which these partitions belong, in the + format of + projects/{project}/catalogs/{catalogs}/databases/{database}/tables/{table}. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, hive_metastore.BatchDeletePartitionsRequest): + request = hive_metastore.BatchDeletePartitionsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.batch_delete_partitions + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def batch_update_partitions( + self, + request: Optional[ + Union[hive_metastore.BatchUpdatePartitionsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> hive_metastore.BatchUpdatePartitionsResponse: + r"""Updates partitions in a table. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import biglake_hive_v1 + + async def sample_batch_update_partitions(): + # Create a client + client = biglake_hive_v1.HiveMetastoreServiceAsyncClient() + + # Initialize request argument(s) + requests = biglake_hive_v1.UpdatePartitionRequest() + requests.partition.values = ['values_value1', 'values_value2'] + + request = biglake_hive_v1.BatchUpdatePartitionsRequest( + parent="parent_value", + requests=requests, + ) + + # Make the request + response = await client.batch_update_partitions(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.biglake_hive_v1.types.BatchUpdatePartitionsRequest, dict]]): + The request object. Request message for + BatchUpdatePartitions. + parent (:class:`str`): + Required. Reference to the table to + which these partitions belong, in the + format of + projects/{project}/catalogs/{catalogs}/databases/{database}/tables/{table}. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.biglake_hive_v1.types.BatchUpdatePartitionsResponse: + Response message for + BatchUpdatePartitions. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, hive_metastore.BatchUpdatePartitionsRequest): + request = hive_metastore.BatchUpdatePartitionsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.batch_update_partitions + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_partitions( + self, + request: Optional[Union[hive_metastore.ListPartitionsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> Awaitable[AsyncIterable[hive_metastore.ListPartitionsResponse]]: + r"""Streams list of partitions from a table. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import biglake_hive_v1 + + async def sample_list_partitions(): + # Create a client + client = biglake_hive_v1.HiveMetastoreServiceAsyncClient() + + # Initialize request argument(s) + request = biglake_hive_v1.ListPartitionsRequest( + parent="parent_value", + ) + + # Make the request + stream = await client.list_partitions(request=request) + + # Handle the response + async for response in stream: + print(response) + + Args: + request (Optional[Union[google.cloud.biglake_hive_v1.types.ListPartitionsRequest, dict]]): + The request object. Request message for ListPartitions. + parent (:class:`str`): + Required. Reference to the table to + which these partitions belong, in the + format of + projects/{project}/catalogs/{catalogs}/databases/{database}/tables/{table}. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + AsyncIterable[google.cloud.biglake_hive_v1.types.ListPartitionsResponse]: + Response message for ListPartitions. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, hive_metastore.ListPartitionsRequest): + request = hive_metastore.ListPartitionsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_partitions + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def failover_hive_catalog( + self, + request: Optional[ + Union[hive_metastore.FailoverHiveCatalogRequest, dict] + ] = None, + *, + name: Optional[str] = None, + primary_replica: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> hive_metastore.FailoverHiveCatalogResponse: + r"""Failover the catalog to a new primary replica region. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import biglake_hive_v1 + + async def sample_failover_hive_catalog(): + # Create a client + client = biglake_hive_v1.HiveMetastoreServiceAsyncClient() + + # Initialize request argument(s) + request = biglake_hive_v1.FailoverHiveCatalogRequest( + name="name_value", + primary_replica="primary_replica_value", + ) + + # Make the request + response = await client.failover_hive_catalog(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.biglake_hive_v1.types.FailoverHiveCatalogRequest, dict]]): + The request object. Request message for + FailoverHiveCatalog. + name (:class:`str`): + Required. The name of the catalog in the form + "projects/{project_id}/catalogs/{catalog_id}" + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + primary_replica (:class:`str`): + Required. The region being assigned + as the new primary replica region. For + example "us-east1". This must be one of + the replica regions in the catalog's + list of replicas marked as a + "secondary". + + This corresponds to the ``primary_replica`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.biglake_hive_v1.types.FailoverHiveCatalogResponse: + Response message for + FailoverHiveCatalog. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name, primary_replica] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, hive_metastore.FailoverHiveCatalogRequest): + request = hive_metastore.FailoverHiveCatalogRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if primary_replica is not None: + request.primary_replica = primary_replica + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.failover_hive_catalog + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self) -> "HiveMetastoreServiceAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) +DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +__all__ = ("HiveMetastoreServiceAsyncClient",) diff --git a/packages/google-cloud-biglake-hive/google/cloud/biglake_hive_v1/services/hive_metastore_service/client.py b/packages/google-cloud-biglake-hive/google/cloud/biglake_hive_v1/services/hive_metastore_service/client.py new file mode 100644 index 000000000000..8f08117d55af --- /dev/null +++ b/packages/google-cloud-biglake-hive/google/cloud/biglake_hive_v1/services/hive_metastore_service/client.py @@ -0,0 +1,3196 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 json +import logging as std_logging +import os +import re +import warnings +from collections import OrderedDict +from http import HTTPStatus +from typing import ( + Callable, + Dict, + Iterable, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) + +import google.protobuf +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.biglake_hive_v1 import gapic_version as package_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore + +from google.cloud.biglake_hive_v1.services.hive_metastore_service import pagers +from google.cloud.biglake_hive_v1.types import hive_metastore + +from .transports.base import DEFAULT_CLIENT_INFO, HiveMetastoreServiceTransport +from .transports.grpc import HiveMetastoreServiceGrpcTransport +from .transports.grpc_asyncio import HiveMetastoreServiceGrpcAsyncIOTransport +from .transports.rest import HiveMetastoreServiceRestTransport + + +class HiveMetastoreServiceClientMeta(type): + """Metaclass for the HiveMetastoreService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = OrderedDict() # type: Dict[str, Type[HiveMetastoreServiceTransport]] + _transport_registry["grpc"] = HiveMetastoreServiceGrpcTransport + _transport_registry["grpc_asyncio"] = HiveMetastoreServiceGrpcAsyncIOTransport + _transport_registry["rest"] = HiveMetastoreServiceRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[HiveMetastoreServiceTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class HiveMetastoreServiceClient(metaclass=HiveMetastoreServiceClientMeta): + """Hive Metastore Service is a biglake service that allows users to + manage their external Hive catalogs. Full API compatibility with OSS + Hive Metastore APIs is not supported. The methods match the Hive + Metastore API spec mostly except for a few exceptions. These include + listing resources with pattern, environment context which are + combined in a single List API, return of ListResponse object instead + of a list of resources, transactions, locks, etc. + + The BigLake Hive Metastore API defines the following resources: + + - A collection of Google Cloud projects: ``/projects/*`` + - Each project has a collection of catalogs: ``/catalogs/*`` + - Each catalog has a collection of databases: ``/databases/*`` + - Each database has a collection of tables: ``/tables/*`` + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint) -> Optional[str]: + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + Optional[str]: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + if m is None: + # Could not parse api_endpoint; return as-is. + return api_endpoint + + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "biglake.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "biglake.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + HiveMetastoreServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + HiveMetastoreServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> HiveMetastoreServiceTransport: + """Returns the transport used by the client instance. + + Returns: + HiveMetastoreServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def catalog_path( + project: str, + catalog: str, + ) -> str: + """Returns a fully-qualified catalog string.""" + return "projects/{project}/catalogs/{catalog}".format( + project=project, + catalog=catalog, + ) + + @staticmethod + def parse_catalog_path(path: str) -> Dict[str, str]: + """Parses a catalog path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/catalogs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def namespace_path( + project: str, + catalog: str, + database: str, + ) -> str: + """Returns a fully-qualified namespace string.""" + return "projects/{project}/catalogs/{catalog}/databases/{database}".format( + project=project, + catalog=catalog, + database=database, + ) + + @staticmethod + def parse_namespace_path(path: str) -> Dict[str, str]: + """Parses a namespace path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/catalogs/(?P.+?)/databases/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def table_path( + project: str, + catalog: str, + database: str, + table: str, + ) -> str: + """Returns a fully-qualified table string.""" + return "projects/{project}/catalogs/{catalog}/databases/{database}/tables/{table}".format( + project=project, + catalog=catalog, + database=database, + table=table, + ) + + @staticmethod + def parse_table_path(path: str) -> Dict[str, str]: + """Parses a table path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/catalogs/(?P.+?)/databases/(?P.+?)/tables/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path( + billing_account: str, + ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path( + folder: str, + ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format( + folder=folder, + ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path( + organization: str, + ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format( + organization=organization, + ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path( + project: str, + ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format( + project=project, + ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path( + project: str, + location: str, + ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = HiveMetastoreServiceClient._use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert: + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = HiveMetastoreServiceClient._use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + return use_client_cert, use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint( + api_override, client_cert_source, universe_domain, use_mtls_endpoint + ) -> str: + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + _default_universe = HiveMetastoreServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = HiveMetastoreServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = HiveMetastoreServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=universe_domain + ) + return api_endpoint + + @staticmethod + def _get_universe_domain( + client_universe_domain: Optional[str], universe_domain_env: Optional[str] + ) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = HiveMetastoreServiceClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True + + def _add_cred_info_for_auth_errors( + self, error: core_exceptions.GoogleAPICallError + ) -> None: + """Adds credential info string to error details for 401/403/404 errors. + + Args: + error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. + """ + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: + return + + cred = self._transport._credentials + + # get_cred_info is only available in google-auth>=2.35.0 + if not hasattr(cred, "get_cred_info"): + return + + # ignore the type check since pypy test fails when get_cred_info + # is not available + cred_info = cred.get_cred_info() # type: ignore + if cred_info and hasattr(error._details, "append"): + error._details.append(json.dumps(cred_info)) + + @property + def api_endpoint(self) -> str: + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[ + str, + HiveMetastoreServiceTransport, + Callable[..., HiveMetastoreServiceTransport], + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the hive metastore service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,HiveMetastoreServiceTransport,Callable[..., HiveMetastoreServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the HiveMetastoreServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) + + universe_domain_opt = getattr(self._client_options, "universe_domain", None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ( + HiveMetastoreServiceClient._read_environment_variables() + ) + self._client_cert_source = HiveMetastoreServiceClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = HiveMetastoreServiceClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) + self._api_endpoint: str = "" # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER + # Setup logging. + client_logging.initialize_logging() + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, HiveMetastoreServiceTransport) + if transport_provided: + # transport is a HiveMetastoreServiceTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes directly." + ) + self._transport = cast(HiveMetastoreServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = ( + self._api_endpoint + or HiveMetastoreServiceClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint, + ) + ) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + + transport_init: Union[ + Type[HiveMetastoreServiceTransport], + Callable[..., HiveMetastoreServiceTransport], + ] = ( + HiveMetastoreServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., HiveMetastoreServiceTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.cloud.biglake.hive_v1.HiveMetastoreServiceClient`.", + extra={ + "serviceName": "google.cloud.biglake.hive.v1.HiveMetastoreService", + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { + "serviceName": "google.cloud.biglake.hive.v1.HiveMetastoreService", + "credentialsType": None, + }, + ) + + def create_hive_catalog( + self, + request: Optional[Union[hive_metastore.CreateHiveCatalogRequest, dict]] = None, + *, + parent: Optional[str] = None, + hive_catalog: Optional[hive_metastore.HiveCatalog] = None, + hive_catalog_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> hive_metastore.HiveCatalog: + r"""Creates a new hive catalog. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import biglake_hive_v1 + + def sample_create_hive_catalog(): + # Create a client + client = biglake_hive_v1.HiveMetastoreServiceClient() + + # Initialize request argument(s) + hive_catalog = biglake_hive_v1.HiveCatalog() + hive_catalog.location_uri = "location_uri_value" + + request = biglake_hive_v1.CreateHiveCatalogRequest( + parent="parent_value", + hive_catalog=hive_catalog, + hive_catalog_id="hive_catalog_id_value", + primary_location="primary_location_value", + ) + + # Make the request + response = client.create_hive_catalog(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.biglake_hive_v1.types.CreateHiveCatalogRequest, dict]): + The request object. Request message for the + CreateHiveCatalog method. + parent (str): + Required. The parent resource where this catalog will be + created. Format: projects/{project_id_or_number} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + hive_catalog (google.cloud.biglake_hive_v1.types.HiveCatalog): + Required. The catalog to create. The ``name`` field does + not need to be provided. Gets copied over from + catalog_id. + + This corresponds to the ``hive_catalog`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + hive_catalog_id (str): + Required. The Hive Catalog ID to use + for the catalog that will become the + final component of the catalog's + resource name. The maximum length is 256 + characters. + + This corresponds to the ``hive_catalog_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.biglake_hive_v1.types.HiveCatalog: + The HiveCatalog contains spark/hive + databases and tables in the BigLake + Metastore. While creating resources + under a catalog, ideally ensure that the + storage bucket location, spark / hive + engine location or any other compute + location match. Catalog can be viewed + as the destination for migrating an + on-prem Hive metastore to GCP. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, hive_catalog, hive_catalog_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, hive_metastore.CreateHiveCatalogRequest): + request = hive_metastore.CreateHiveCatalogRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if hive_catalog is not None: + request.hive_catalog = hive_catalog + if hive_catalog_id is not None: + request.hive_catalog_id = hive_catalog_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_hive_catalog] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_hive_catalog( + self, + request: Optional[Union[hive_metastore.GetHiveCatalogRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> hive_metastore.HiveCatalog: + r"""Gets the catalog specified by the resource name. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import biglake_hive_v1 + + def sample_get_hive_catalog(): + # Create a client + client = biglake_hive_v1.HiveMetastoreServiceClient() + + # Initialize request argument(s) + request = biglake_hive_v1.GetHiveCatalogRequest( + name="name_value", + ) + + # Make the request + response = client.get_hive_catalog(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.biglake_hive_v1.types.GetHiveCatalogRequest, dict]): + The request object. Request message for the + GetHiveCatalog method. + name (str): + Required. The name of the catalog to retrieve. Format: + projects/{project_id_or_number}/catalogs/{catalog_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.biglake_hive_v1.types.HiveCatalog: + The HiveCatalog contains spark/hive + databases and tables in the BigLake + Metastore. While creating resources + under a catalog, ideally ensure that the + storage bucket location, spark / hive + engine location or any other compute + location match. Catalog can be viewed + as the destination for migrating an + on-prem Hive metastore to GCP. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, hive_metastore.GetHiveCatalogRequest): + request = hive_metastore.GetHiveCatalogRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_hive_catalog] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_hive_catalogs( + self, + request: Optional[Union[hive_metastore.ListHiveCatalogsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListHiveCatalogsPager: + r"""List all catalogs in a specified project. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import biglake_hive_v1 + + def sample_list_hive_catalogs(): + # Create a client + client = biglake_hive_v1.HiveMetastoreServiceClient() + + # Initialize request argument(s) + request = biglake_hive_v1.ListHiveCatalogsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_hive_catalogs(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.biglake_hive_v1.types.ListHiveCatalogsRequest, dict]): + The request object. Request message for the + ListHiveCatalogs method. + parent (str): + Required. The project to list catalogs from. Format: + projects/{project_id_or_number} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.biglake_hive_v1.services.hive_metastore_service.pagers.ListHiveCatalogsPager: + Response message for the + ListHiveCatalogs method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, hive_metastore.ListHiveCatalogsRequest): + request = hive_metastore.ListHiveCatalogsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_hive_catalogs] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListHiveCatalogsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_hive_catalog( + self, + request: Optional[Union[hive_metastore.UpdateHiveCatalogRequest, dict]] = None, + *, + hive_catalog: Optional[hive_metastore.HiveCatalog] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> hive_metastore.HiveCatalog: + r"""Updates an existing catalog. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import biglake_hive_v1 + + def sample_update_hive_catalog(): + # Create a client + client = biglake_hive_v1.HiveMetastoreServiceClient() + + # Initialize request argument(s) + hive_catalog = biglake_hive_v1.HiveCatalog() + hive_catalog.location_uri = "location_uri_value" + + request = biglake_hive_v1.UpdateHiveCatalogRequest( + hive_catalog=hive_catalog, + ) + + # Make the request + response = client.update_hive_catalog(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.biglake_hive_v1.types.UpdateHiveCatalogRequest, dict]): + The request object. Request message for the + UpdateHiveCatalog method. + hive_catalog (google.cloud.biglake_hive_v1.types.HiveCatalog): + Required. The hive catalog to update. The name under the + catalog is used to identify the catalog. Format: + projects/{project_id_or_number}/catalogs/{catalog_id} + + This corresponds to the ``hive_catalog`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The list of fields to update. + + For the ``FieldMask`` definition, see + https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask + If not set, defaults to all of the fields that are + allowed to update. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.biglake_hive_v1.types.HiveCatalog: + The HiveCatalog contains spark/hive + databases and tables in the BigLake + Metastore. While creating resources + under a catalog, ideally ensure that the + storage bucket location, spark / hive + engine location or any other compute + location match. Catalog can be viewed + as the destination for migrating an + on-prem Hive metastore to GCP. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [hive_catalog, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, hive_metastore.UpdateHiveCatalogRequest): + request = hive_metastore.UpdateHiveCatalogRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if hive_catalog is not None: + request.hive_catalog = hive_catalog + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_hive_catalog] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("hive_catalog.name", request.hive_catalog.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_hive_catalog( + self, + request: Optional[Union[hive_metastore.DeleteHiveCatalogRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes an existing catalog specified by the catalog + ID. Delete will fail if the catalog is not empty. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import biglake_hive_v1 + + def sample_delete_hive_catalog(): + # Create a client + client = biglake_hive_v1.HiveMetastoreServiceClient() + + # Initialize request argument(s) + request = biglake_hive_v1.DeleteHiveCatalogRequest( + name="name_value", + ) + + # Make the request + client.delete_hive_catalog(request=request) + + Args: + request (Union[google.cloud.biglake_hive_v1.types.DeleteHiveCatalogRequest, dict]): + The request object. Request message for the + DeleteHiveCatalog method. + name (str): + Required. The name of the catalog to delete. Format: + projects/{project_id_or_number}/catalogs/{catalog_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, hive_metastore.DeleteHiveCatalogRequest): + request = hive_metastore.DeleteHiveCatalogRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_hive_catalog] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def create_hive_database( + self, + request: Optional[Union[hive_metastore.CreateHiveDatabaseRequest, dict]] = None, + *, + parent: Optional[str] = None, + hive_database: Optional[hive_metastore.HiveDatabase] = None, + hive_database_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> hive_metastore.HiveDatabase: + r"""Creates a new database. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import biglake_hive_v1 + + def sample_create_hive_database(): + # Create a client + client = biglake_hive_v1.HiveMetastoreServiceClient() + + # Initialize request argument(s) + request = biglake_hive_v1.CreateHiveDatabaseRequest( + parent="parent_value", + hive_database_id="hive_database_id_value", + ) + + # Make the request + response = client.create_hive_database(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.biglake_hive_v1.types.CreateHiveDatabaseRequest, dict]): + The request object. Request message for the + CreateHiveDatabase method. + parent (str): + Required. The parent resource where this database will + be created. Format: + projects/{project_id_or_number}/catalogs/{catalog_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + hive_database (google.cloud.biglake_hive_v1.types.HiveDatabase): + Required. The database to create. The ``name`` field + does not need to be provided. + + This corresponds to the ``hive_database`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + hive_database_id (str): + Required. The ID to use for the Hive + Database. The maximum length is 128 + characters. + + This corresponds to the ``hive_database_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.biglake_hive_v1.types.HiveDatabase: + Stores the hive database information. + It includes the database name, + description, location and properties + associated with the database. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, hive_database, hive_database_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, hive_metastore.CreateHiveDatabaseRequest): + request = hive_metastore.CreateHiveDatabaseRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if hive_database is not None: + request.hive_database = hive_database + if hive_database_id is not None: + request.hive_database_id = hive_database_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_hive_database] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_hive_database( + self, + request: Optional[Union[hive_metastore.GetHiveDatabaseRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> hive_metastore.HiveDatabase: + r"""Gets the database specified by the resource name. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import biglake_hive_v1 + + def sample_get_hive_database(): + # Create a client + client = biglake_hive_v1.HiveMetastoreServiceClient() + + # Initialize request argument(s) + request = biglake_hive_v1.GetHiveDatabaseRequest( + name="name_value", + ) + + # Make the request + response = client.get_hive_database(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.biglake_hive_v1.types.GetHiveDatabaseRequest, dict]): + The request object. Request message for the + GetHiveDatabase method. + name (str): + Required. The name of the database to retrieve. Format: + projects/{project_id_or_number}/catalogs/{catalog_id}/databases/{database_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.biglake_hive_v1.types.HiveDatabase: + Stores the hive database information. + It includes the database name, + description, location and properties + associated with the database. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, hive_metastore.GetHiveDatabaseRequest): + request = hive_metastore.GetHiveDatabaseRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_hive_database] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_hive_databases( + self, + request: Optional[Union[hive_metastore.ListHiveDatabasesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListHiveDatabasesPager: + r"""List all databases in a specified catalog. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import biglake_hive_v1 + + def sample_list_hive_databases(): + # Create a client + client = biglake_hive_v1.HiveMetastoreServiceClient() + + # Initialize request argument(s) + request = biglake_hive_v1.ListHiveDatabasesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_hive_databases(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.biglake_hive_v1.types.ListHiveDatabasesRequest, dict]): + The request object. Request message for the + ListHiveDatabases method. + parent (str): + Required. The hive catalog to list databases from. + Format: + projects/{project_id_or_number}/catalogs/{catalog_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.biglake_hive_v1.services.hive_metastore_service.pagers.ListHiveDatabasesPager: + Response message for the + ListHiveDatabases method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, hive_metastore.ListHiveDatabasesRequest): + request = hive_metastore.ListHiveDatabasesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_hive_databases] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListHiveDatabasesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_hive_database( + self, + request: Optional[Union[hive_metastore.UpdateHiveDatabaseRequest, dict]] = None, + *, + hive_database: Optional[hive_metastore.HiveDatabase] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> hive_metastore.HiveDatabase: + r"""Updates an existing database specified by the + database name. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import biglake_hive_v1 + + def sample_update_hive_database(): + # Create a client + client = biglake_hive_v1.HiveMetastoreServiceClient() + + # Initialize request argument(s) + request = biglake_hive_v1.UpdateHiveDatabaseRequest( + ) + + # Make the request + response = client.update_hive_database(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.biglake_hive_v1.types.UpdateHiveDatabaseRequest, dict]): + The request object. Request message for the + UpdateHiveDatabase method. + hive_database (google.cloud.biglake_hive_v1.types.HiveDatabase): + Required. The database to update. + + The database's ``name`` field is used to identify the + database to update. Format: + projects/{project_id_or_number}/catalogs/{catalog_id}/databases/{database_id} + + This corresponds to the ``hive_database`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The list of fields to + update. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.biglake_hive_v1.types.HiveDatabase: + Stores the hive database information. + It includes the database name, + description, location and properties + associated with the database. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [hive_database, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, hive_metastore.UpdateHiveDatabaseRequest): + request = hive_metastore.UpdateHiveDatabaseRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if hive_database is not None: + request.hive_database = hive_database + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_hive_database] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("hive_database.name", request.hive_database.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_hive_database( + self, + request: Optional[Union[hive_metastore.DeleteHiveDatabaseRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes an existing database specified by the + database name. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import biglake_hive_v1 + + def sample_delete_hive_database(): + # Create a client + client = biglake_hive_v1.HiveMetastoreServiceClient() + + # Initialize request argument(s) + request = biglake_hive_v1.DeleteHiveDatabaseRequest( + name="name_value", + ) + + # Make the request + client.delete_hive_database(request=request) + + Args: + request (Union[google.cloud.biglake_hive_v1.types.DeleteHiveDatabaseRequest, dict]): + The request object. Request message for the + DeleteHiveDatabase method. + name (str): + Required. The name of the database to delete. Format: + projects/{project_id_or_number}/catalogs/{catalog_id}/databases/{database_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, hive_metastore.DeleteHiveDatabaseRequest): + request = hive_metastore.DeleteHiveDatabaseRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_hive_database] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def create_hive_table( + self, + request: Optional[Union[hive_metastore.CreateHiveTableRequest, dict]] = None, + *, + parent: Optional[str] = None, + hive_table: Optional[hive_metastore.HiveTable] = None, + hive_table_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> hive_metastore.HiveTable: + r"""Creates a new hive table. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import biglake_hive_v1 + + def sample_create_hive_table(): + # Create a client + client = biglake_hive_v1.HiveMetastoreServiceClient() + + # Initialize request argument(s) + hive_table = biglake_hive_v1.HiveTable() + hive_table.storage_descriptor.columns.name = "name_value" + hive_table.storage_descriptor.columns.type_ = "type__value" + + request = biglake_hive_v1.CreateHiveTableRequest( + parent="parent_value", + hive_table=hive_table, + hive_table_id="hive_table_id_value", + ) + + # Make the request + response = client.create_hive_table(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.biglake_hive_v1.types.CreateHiveTableRequest, dict]): + The request object. Request message for the + CreateHiveTable method. + parent (str): + Required. The parent resource for the table to be + created. Format: + projects/{project_id_or_number}/catalogs/{catalog_id}/databases/{database_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + hive_table (google.cloud.biglake_hive_v1.types.HiveTable): + Required. The Hive Table to create. The ``name`` field + does not need to be provided. + + This corresponds to the ``hive_table`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + hive_table_id (str): + Required. The Hive Table ID to use + for the table that will become the final + component of the table's resource name. + The maximum length is 256 characters. + + This corresponds to the ``hive_table_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.biglake_hive_v1.types.HiveTable: + Stores the hive table information. It + includes the table name, schema (column + names and types), data location, storage + format, serde info, etc. This message + closely matches the Table object in the + IMetastoreClient + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, hive_table, hive_table_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, hive_metastore.CreateHiveTableRequest): + request = hive_metastore.CreateHiveTableRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if hive_table is not None: + request.hive_table = hive_table + if hive_table_id is not None: + request.hive_table_id = hive_table_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_hive_table] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_hive_table( + self, + request: Optional[Union[hive_metastore.GetHiveTableRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> hive_metastore.HiveTable: + r"""Gets the table specified by the resource name. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import biglake_hive_v1 + + def sample_get_hive_table(): + # Create a client + client = biglake_hive_v1.HiveMetastoreServiceClient() + + # Initialize request argument(s) + request = biglake_hive_v1.GetHiveTableRequest( + name="name_value", + ) + + # Make the request + response = client.get_hive_table(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.biglake_hive_v1.types.GetHiveTableRequest, dict]): + The request object. Request message for the GetHiveTable + method. + name (str): + Required. The name of the table to retrieve. Format: + projects/{project_id_or_number}/catalogs/{catalog_id}/databases/{database_id}/tables/{table_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.biglake_hive_v1.types.HiveTable: + Stores the hive table information. It + includes the table name, schema (column + names and types), data location, storage + format, serde info, etc. This message + closely matches the Table object in the + IMetastoreClient + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, hive_metastore.GetHiveTableRequest): + request = hive_metastore.GetHiveTableRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_hive_table] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_hive_tables( + self, + request: Optional[Union[hive_metastore.ListHiveTablesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListHiveTablesPager: + r"""List all hive tables in a specified project under the + hive catalog and database. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import biglake_hive_v1 + + def sample_list_hive_tables(): + # Create a client + client = biglake_hive_v1.HiveMetastoreServiceClient() + + # Initialize request argument(s) + request = biglake_hive_v1.ListHiveTablesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_hive_tables(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.biglake_hive_v1.types.ListHiveTablesRequest, dict]): + The request object. Request message for the + ListHiveTables method. + parent (str): + Required. The database to list tables from. Format: + projects/{project_id_or_number}/catalogs/{catalog_id}/databases/{database_id} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.biglake_hive_v1.services.hive_metastore_service.pagers.ListHiveTablesPager: + Response message for the + ListHiveTables method. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, hive_metastore.ListHiveTablesRequest): + request = hive_metastore.ListHiveTablesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_hive_tables] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListHiveTablesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_hive_table( + self, + request: Optional[Union[hive_metastore.UpdateHiveTableRequest, dict]] = None, + *, + hive_table: Optional[hive_metastore.HiveTable] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> hive_metastore.HiveTable: + r"""Updates an existing table specified by the table + name. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import biglake_hive_v1 + + def sample_update_hive_table(): + # Create a client + client = biglake_hive_v1.HiveMetastoreServiceClient() + + # Initialize request argument(s) + hive_table = biglake_hive_v1.HiveTable() + hive_table.storage_descriptor.columns.name = "name_value" + hive_table.storage_descriptor.columns.type_ = "type__value" + + request = biglake_hive_v1.UpdateHiveTableRequest( + hive_table=hive_table, + ) + + # Make the request + response = client.update_hive_table(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.biglake_hive_v1.types.UpdateHiveTableRequest, dict]): + The request object. Request message for the + UpdateHiveTable method. + hive_table (google.cloud.biglake_hive_v1.types.HiveTable): + Required. The table to update. + + The table's ``name`` field is used to identify the table + to update. Format: + projects/{project_id_or_number}/catalogs/{catalog_id}/databases/{database_id}/tables/{table_id} + + This corresponds to the ``hive_table`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The list of fields to + update. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.biglake_hive_v1.types.HiveTable: + Stores the hive table information. It + includes the table name, schema (column + names and types), data location, storage + format, serde info, etc. This message + closely matches the Table object in the + IMetastoreClient + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [hive_table, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, hive_metastore.UpdateHiveTableRequest): + request = hive_metastore.UpdateHiveTableRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if hive_table is not None: + request.hive_table = hive_table + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_hive_table] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("hive_table.name", request.hive_table.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_hive_table( + self, + request: Optional[Union[hive_metastore.DeleteHiveTableRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes an existing table specified by the table + name. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import biglake_hive_v1 + + def sample_delete_hive_table(): + # Create a client + client = biglake_hive_v1.HiveMetastoreServiceClient() + + # Initialize request argument(s) + request = biglake_hive_v1.DeleteHiveTableRequest( + name="name_value", + ) + + # Make the request + client.delete_hive_table(request=request) + + Args: + request (Union[google.cloud.biglake_hive_v1.types.DeleteHiveTableRequest, dict]): + The request object. Request message for the + DeleteHiveTable method. + name (str): + Required. The name of the database to delete. Format: + projects/{project_id_or_number}/catalogs/{catalog_id}/databases/{database_id}/tables/{table_id} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, hive_metastore.DeleteHiveTableRequest): + request = hive_metastore.DeleteHiveTableRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_hive_table] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def batch_create_partitions( + self, + request: Optional[ + Union[hive_metastore.BatchCreatePartitionsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> hive_metastore.BatchCreatePartitionsResponse: + r"""Adds partitions to a table. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import biglake_hive_v1 + + def sample_batch_create_partitions(): + # Create a client + client = biglake_hive_v1.HiveMetastoreServiceClient() + + # Initialize request argument(s) + requests = biglake_hive_v1.CreatePartitionRequest() + requests.parent = "parent_value" + requests.partition.values = ['values_value1', 'values_value2'] + + request = biglake_hive_v1.BatchCreatePartitionsRequest( + parent="parent_value", + requests=requests, + ) + + # Make the request + response = client.batch_create_partitions(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.biglake_hive_v1.types.BatchCreatePartitionsRequest, dict]): + The request object. Request message for the + BatchCreatePartitions method. + parent (str): + Required. Reference to the table to + where the partitions to be added, in the + format of + projects/{project}/catalogs/{catalogs}/databases/{database}/tables/{table}. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.biglake_hive_v1.types.BatchCreatePartitionsResponse: + Response message for + BatchCreatePartitions. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, hive_metastore.BatchCreatePartitionsRequest): + request = hive_metastore.BatchCreatePartitionsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.batch_create_partitions] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def batch_delete_partitions( + self, + request: Optional[ + Union[hive_metastore.BatchDeletePartitionsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes partitions from a table. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import biglake_hive_v1 + + def sample_batch_delete_partitions(): + # Create a client + client = biglake_hive_v1.HiveMetastoreServiceClient() + + # Initialize request argument(s) + partition_values = biglake_hive_v1.PartitionValues() + partition_values.values = ['values_value1', 'values_value2'] + + request = biglake_hive_v1.BatchDeletePartitionsRequest( + parent="parent_value", + partition_values=partition_values, + ) + + # Make the request + client.batch_delete_partitions(request=request) + + Args: + request (Union[google.cloud.biglake_hive_v1.types.BatchDeletePartitionsRequest, dict]): + The request object. Request message for + BatchDeletePartitions. The Partition is + uniquely identified by values, which is + an ordered list. Hence, there is no + separate name or partition id field. + parent (str): + Required. Reference to the table to + which these partitions belong, in the + format of + projects/{project}/catalogs/{catalogs}/databases/{database}/tables/{table}. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, hive_metastore.BatchDeletePartitionsRequest): + request = hive_metastore.BatchDeletePartitionsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.batch_delete_partitions] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def batch_update_partitions( + self, + request: Optional[ + Union[hive_metastore.BatchUpdatePartitionsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> hive_metastore.BatchUpdatePartitionsResponse: + r"""Updates partitions in a table. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import biglake_hive_v1 + + def sample_batch_update_partitions(): + # Create a client + client = biglake_hive_v1.HiveMetastoreServiceClient() + + # Initialize request argument(s) + requests = biglake_hive_v1.UpdatePartitionRequest() + requests.partition.values = ['values_value1', 'values_value2'] + + request = biglake_hive_v1.BatchUpdatePartitionsRequest( + parent="parent_value", + requests=requests, + ) + + # Make the request + response = client.batch_update_partitions(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.biglake_hive_v1.types.BatchUpdatePartitionsRequest, dict]): + The request object. Request message for + BatchUpdatePartitions. + parent (str): + Required. Reference to the table to + which these partitions belong, in the + format of + projects/{project}/catalogs/{catalogs}/databases/{database}/tables/{table}. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.biglake_hive_v1.types.BatchUpdatePartitionsResponse: + Response message for + BatchUpdatePartitions. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, hive_metastore.BatchUpdatePartitionsRequest): + request = hive_metastore.BatchUpdatePartitionsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.batch_update_partitions] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_partitions( + self, + request: Optional[Union[hive_metastore.ListPartitionsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> Iterable[hive_metastore.ListPartitionsResponse]: + r"""Streams list of partitions from a table. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import biglake_hive_v1 + + def sample_list_partitions(): + # Create a client + client = biglake_hive_v1.HiveMetastoreServiceClient() + + # Initialize request argument(s) + request = biglake_hive_v1.ListPartitionsRequest( + parent="parent_value", + ) + + # Make the request + stream = client.list_partitions(request=request) + + # Handle the response + for response in stream: + print(response) + + Args: + request (Union[google.cloud.biglake_hive_v1.types.ListPartitionsRequest, dict]): + The request object. Request message for ListPartitions. + parent (str): + Required. Reference to the table to + which these partitions belong, in the + format of + projects/{project}/catalogs/{catalogs}/databases/{database}/tables/{table}. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + Iterable[google.cloud.biglake_hive_v1.types.ListPartitionsResponse]: + Response message for ListPartitions. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, hive_metastore.ListPartitionsRequest): + request = hive_metastore.ListPartitionsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_partitions] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def failover_hive_catalog( + self, + request: Optional[ + Union[hive_metastore.FailoverHiveCatalogRequest, dict] + ] = None, + *, + name: Optional[str] = None, + primary_replica: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> hive_metastore.FailoverHiveCatalogResponse: + r"""Failover the catalog to a new primary replica region. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import biglake_hive_v1 + + def sample_failover_hive_catalog(): + # Create a client + client = biglake_hive_v1.HiveMetastoreServiceClient() + + # Initialize request argument(s) + request = biglake_hive_v1.FailoverHiveCatalogRequest( + name="name_value", + primary_replica="primary_replica_value", + ) + + # Make the request + response = client.failover_hive_catalog(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.biglake_hive_v1.types.FailoverHiveCatalogRequest, dict]): + The request object. Request message for + FailoverHiveCatalog. + name (str): + Required. The name of the catalog in the form + "projects/{project_id}/catalogs/{catalog_id}" + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + primary_replica (str): + Required. The region being assigned + as the new primary replica region. For + example "us-east1". This must be one of + the replica regions in the catalog's + list of replicas marked as a + "secondary". + + This corresponds to the ``primary_replica`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.biglake_hive_v1.types.FailoverHiveCatalogResponse: + Response message for + FailoverHiveCatalog. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name, primary_replica] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, hive_metastore.FailoverHiveCatalogRequest): + request = hive_metastore.FailoverHiveCatalogRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if primary_replica is not None: + request.primary_replica = primary_replica + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.failover_hive_catalog] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "HiveMetastoreServiceClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) +DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + +__all__ = ("HiveMetastoreServiceClient",) diff --git a/packages/google-cloud-biglake-hive/google/cloud/biglake_hive_v1/services/hive_metastore_service/pagers.py b/packages/google-cloud-biglake-hive/google/cloud/biglake_hive_v1/services/hive_metastore_service/pagers.py new file mode 100644 index 000000000000..9f72c7f36483 --- /dev/null +++ b/packages/google-cloud-biglake-hive/google/cloud/biglake_hive_v1/services/hive_metastore_service/pagers.py @@ -0,0 +1,509 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 ( + Any, + AsyncIterator, + Awaitable, + Callable, + Iterator, + Optional, + Sequence, + Tuple, + Union, +) + +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import retry_async as retries_async + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] + OptionalAsyncRetry = Union[ + retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None + ] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore + +from google.cloud.biglake_hive_v1.types import hive_metastore + + +class ListHiveCatalogsPager: + """A pager for iterating through ``list_hive_catalogs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.biglake_hive_v1.types.ListHiveCatalogsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``catalogs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListHiveCatalogs`` requests and continue to iterate + through the ``catalogs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.biglake_hive_v1.types.ListHiveCatalogsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., hive_metastore.ListHiveCatalogsResponse], + request: hive_metastore.ListHiveCatalogsRequest, + response: hive_metastore.ListHiveCatalogsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.biglake_hive_v1.types.ListHiveCatalogsRequest): + The initial request object. + response (google.cloud.biglake_hive_v1.types.ListHiveCatalogsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = hive_metastore.ListHiveCatalogsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[hive_metastore.ListHiveCatalogsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[hive_metastore.HiveCatalog]: + for page in self.pages: + yield from page.catalogs + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListHiveCatalogsAsyncPager: + """A pager for iterating through ``list_hive_catalogs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.biglake_hive_v1.types.ListHiveCatalogsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``catalogs`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListHiveCatalogs`` requests and continue to iterate + through the ``catalogs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.biglake_hive_v1.types.ListHiveCatalogsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[hive_metastore.ListHiveCatalogsResponse]], + request: hive_metastore.ListHiveCatalogsRequest, + response: hive_metastore.ListHiveCatalogsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.biglake_hive_v1.types.ListHiveCatalogsRequest): + The initial request object. + response (google.cloud.biglake_hive_v1.types.ListHiveCatalogsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = hive_metastore.ListHiveCatalogsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[hive_metastore.ListHiveCatalogsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[hive_metastore.HiveCatalog]: + async def async_generator(): + async for page in self.pages: + for response in page.catalogs: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListHiveDatabasesPager: + """A pager for iterating through ``list_hive_databases`` requests. + + This class thinly wraps an initial + :class:`google.cloud.biglake_hive_v1.types.ListHiveDatabasesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``databases`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListHiveDatabases`` requests and continue to iterate + through the ``databases`` field on the + corresponding responses. + + All the usual :class:`google.cloud.biglake_hive_v1.types.ListHiveDatabasesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., hive_metastore.ListHiveDatabasesResponse], + request: hive_metastore.ListHiveDatabasesRequest, + response: hive_metastore.ListHiveDatabasesResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.biglake_hive_v1.types.ListHiveDatabasesRequest): + The initial request object. + response (google.cloud.biglake_hive_v1.types.ListHiveDatabasesResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = hive_metastore.ListHiveDatabasesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[hive_metastore.ListHiveDatabasesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[hive_metastore.HiveDatabase]: + for page in self.pages: + yield from page.databases + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListHiveDatabasesAsyncPager: + """A pager for iterating through ``list_hive_databases`` requests. + + This class thinly wraps an initial + :class:`google.cloud.biglake_hive_v1.types.ListHiveDatabasesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``databases`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListHiveDatabases`` requests and continue to iterate + through the ``databases`` field on the + corresponding responses. + + All the usual :class:`google.cloud.biglake_hive_v1.types.ListHiveDatabasesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[hive_metastore.ListHiveDatabasesResponse]], + request: hive_metastore.ListHiveDatabasesRequest, + response: hive_metastore.ListHiveDatabasesResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.biglake_hive_v1.types.ListHiveDatabasesRequest): + The initial request object. + response (google.cloud.biglake_hive_v1.types.ListHiveDatabasesResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = hive_metastore.ListHiveDatabasesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[hive_metastore.ListHiveDatabasesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[hive_metastore.HiveDatabase]: + async def async_generator(): + async for page in self.pages: + for response in page.databases: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListHiveTablesPager: + """A pager for iterating through ``list_hive_tables`` requests. + + This class thinly wraps an initial + :class:`google.cloud.biglake_hive_v1.types.ListHiveTablesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``tables`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListHiveTables`` requests and continue to iterate + through the ``tables`` field on the + corresponding responses. + + All the usual :class:`google.cloud.biglake_hive_v1.types.ListHiveTablesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., hive_metastore.ListHiveTablesResponse], + request: hive_metastore.ListHiveTablesRequest, + response: hive_metastore.ListHiveTablesResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.biglake_hive_v1.types.ListHiveTablesRequest): + The initial request object. + response (google.cloud.biglake_hive_v1.types.ListHiveTablesResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = hive_metastore.ListHiveTablesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[hive_metastore.ListHiveTablesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[hive_metastore.HiveTable]: + for page in self.pages: + yield from page.tables + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListHiveTablesAsyncPager: + """A pager for iterating through ``list_hive_tables`` requests. + + This class thinly wraps an initial + :class:`google.cloud.biglake_hive_v1.types.ListHiveTablesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``tables`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListHiveTables`` requests and continue to iterate + through the ``tables`` field on the + corresponding responses. + + All the usual :class:`google.cloud.biglake_hive_v1.types.ListHiveTablesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[hive_metastore.ListHiveTablesResponse]], + request: hive_metastore.ListHiveTablesRequest, + response: hive_metastore.ListHiveTablesResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.biglake_hive_v1.types.ListHiveTablesRequest): + The initial request object. + response (google.cloud.biglake_hive_v1.types.ListHiveTablesResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = hive_metastore.ListHiveTablesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[hive_metastore.ListHiveTablesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[hive_metastore.HiveTable]: + async def async_generator(): + async for page in self.pages: + for response in page.tables: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/packages/google-cloud-biglake-hive/google/cloud/biglake_hive_v1/services/hive_metastore_service/transports/README.rst b/packages/google-cloud-biglake-hive/google/cloud/biglake_hive_v1/services/hive_metastore_service/transports/README.rst new file mode 100644 index 000000000000..b67e1685bf2f --- /dev/null +++ b/packages/google-cloud-biglake-hive/google/cloud/biglake_hive_v1/services/hive_metastore_service/transports/README.rst @@ -0,0 +1,10 @@ + +transport inheritance structure +_______________________________ + +``HiveMetastoreServiceTransport`` is the ABC for all transports. + +- public child ``HiveMetastoreServiceGrpcTransport`` for sync gRPC transport (defined in ``grpc.py``). +- public child ``HiveMetastoreServiceGrpcAsyncIOTransport`` for async gRPC transport (defined in ``grpc_asyncio.py``). +- private child ``_BaseHiveMetastoreServiceRestTransport`` for base REST transport with inner classes ``_BaseMETHOD`` (defined in ``rest_base.py``). +- public child ``HiveMetastoreServiceRestTransport`` for sync REST transport with inner classes ``METHOD`` derived from the parent's corresponding ``_BaseMETHOD`` classes (defined in ``rest.py``). diff --git a/packages/google-cloud-biglake-hive/google/cloud/biglake_hive_v1/services/hive_metastore_service/transports/__init__.py b/packages/google-cloud-biglake-hive/google/cloud/biglake_hive_v1/services/hive_metastore_service/transports/__init__.py new file mode 100644 index 000000000000..3398d93bcc79 --- /dev/null +++ b/packages/google-cloud-biglake-hive/google/cloud/biglake_hive_v1/services/hive_metastore_service/transports/__init__.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 OrderedDict +from typing import Dict, Type + +from .base import HiveMetastoreServiceTransport +from .grpc import HiveMetastoreServiceGrpcTransport +from .grpc_asyncio import HiveMetastoreServiceGrpcAsyncIOTransport +from .rest import HiveMetastoreServiceRestInterceptor, HiveMetastoreServiceRestTransport + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[HiveMetastoreServiceTransport]] +_transport_registry["grpc"] = HiveMetastoreServiceGrpcTransport +_transport_registry["grpc_asyncio"] = HiveMetastoreServiceGrpcAsyncIOTransport +_transport_registry["rest"] = HiveMetastoreServiceRestTransport + +__all__ = ( + "HiveMetastoreServiceTransport", + "HiveMetastoreServiceGrpcTransport", + "HiveMetastoreServiceGrpcAsyncIOTransport", + "HiveMetastoreServiceRestTransport", + "HiveMetastoreServiceRestInterceptor", +) diff --git a/packages/google-cloud-biglake-hive/google/cloud/biglake_hive_v1/services/hive_metastore_service/transports/base.py b/packages/google-cloud-biglake-hive/google/cloud/biglake_hive_v1/services/hive_metastore_service/transports/base.py new file mode 100644 index 000000000000..5f25ccb67bd3 --- /dev/null +++ b/packages/google-cloud-biglake-hive/google/cloud/biglake_hive_v1/services/hive_metastore_service/transports/base.py @@ -0,0 +1,464 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 Awaitable, Callable, Dict, Optional, Sequence, Union + +import google.api_core +import google.auth # type: ignore +import google.protobuf +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.biglake_hive_v1 import gapic_version as package_version +from google.cloud.biglake_hive_v1.types import hive_metastore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) +DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class HiveMetastoreServiceTransport(abc.ABC): + """Abstract transport class for HiveMetastoreService.""" + + AUTH_SCOPES = ( + "https://www.googleapis.com/auth/bigquery", + "https://www.googleapis.com/auth/cloud-platform", + ) + + DEFAULT_HOST: str = "biglake.googleapis.com" + + def __init__( + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'biglake.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + + # Save the scopes. + self._scopes = scopes + if not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default( + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + self._wrapped_methods: Dict[Callable, Callable] = {} + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_hive_catalog: gapic_v1.method.wrap_method( + self.create_hive_catalog, + default_timeout=None, + client_info=client_info, + ), + self.get_hive_catalog: gapic_v1.method.wrap_method( + self.get_hive_catalog, + default_timeout=None, + client_info=client_info, + ), + self.list_hive_catalogs: gapic_v1.method.wrap_method( + self.list_hive_catalogs, + default_timeout=None, + client_info=client_info, + ), + self.update_hive_catalog: gapic_v1.method.wrap_method( + self.update_hive_catalog, + default_timeout=None, + client_info=client_info, + ), + self.delete_hive_catalog: gapic_v1.method.wrap_method( + self.delete_hive_catalog, + default_timeout=None, + client_info=client_info, + ), + self.create_hive_database: gapic_v1.method.wrap_method( + self.create_hive_database, + default_timeout=None, + client_info=client_info, + ), + self.get_hive_database: gapic_v1.method.wrap_method( + self.get_hive_database, + default_timeout=None, + client_info=client_info, + ), + self.list_hive_databases: gapic_v1.method.wrap_method( + self.list_hive_databases, + default_timeout=None, + client_info=client_info, + ), + self.update_hive_database: gapic_v1.method.wrap_method( + self.update_hive_database, + default_timeout=None, + client_info=client_info, + ), + self.delete_hive_database: gapic_v1.method.wrap_method( + self.delete_hive_database, + default_timeout=None, + client_info=client_info, + ), + self.create_hive_table: gapic_v1.method.wrap_method( + self.create_hive_table, + default_timeout=None, + client_info=client_info, + ), + self.get_hive_table: gapic_v1.method.wrap_method( + self.get_hive_table, + default_timeout=None, + client_info=client_info, + ), + self.list_hive_tables: gapic_v1.method.wrap_method( + self.list_hive_tables, + default_timeout=None, + client_info=client_info, + ), + self.update_hive_table: gapic_v1.method.wrap_method( + self.update_hive_table, + default_timeout=None, + client_info=client_info, + ), + self.delete_hive_table: gapic_v1.method.wrap_method( + self.delete_hive_table, + default_timeout=None, + client_info=client_info, + ), + self.batch_create_partitions: gapic_v1.method.wrap_method( + self.batch_create_partitions, + default_timeout=None, + client_info=client_info, + ), + self.batch_delete_partitions: gapic_v1.method.wrap_method( + self.batch_delete_partitions, + default_timeout=None, + client_info=client_info, + ), + self.batch_update_partitions: gapic_v1.method.wrap_method( + self.batch_update_partitions, + default_timeout=None, + client_info=client_info, + ), + self.list_partitions: gapic_v1.method.wrap_method( + self.list_partitions, + default_timeout=None, + client_info=client_info, + ), + self.failover_hive_catalog: gapic_v1.method.wrap_method( + self.failover_hive_catalog, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def create_hive_catalog( + self, + ) -> Callable[ + [hive_metastore.CreateHiveCatalogRequest], + Union[hive_metastore.HiveCatalog, Awaitable[hive_metastore.HiveCatalog]], + ]: + raise NotImplementedError() + + @property + def get_hive_catalog( + self, + ) -> Callable[ + [hive_metastore.GetHiveCatalogRequest], + Union[hive_metastore.HiveCatalog, Awaitable[hive_metastore.HiveCatalog]], + ]: + raise NotImplementedError() + + @property + def list_hive_catalogs( + self, + ) -> Callable[ + [hive_metastore.ListHiveCatalogsRequest], + Union[ + hive_metastore.ListHiveCatalogsResponse, + Awaitable[hive_metastore.ListHiveCatalogsResponse], + ], + ]: + raise NotImplementedError() + + @property + def update_hive_catalog( + self, + ) -> Callable[ + [hive_metastore.UpdateHiveCatalogRequest], + Union[hive_metastore.HiveCatalog, Awaitable[hive_metastore.HiveCatalog]], + ]: + raise NotImplementedError() + + @property + def delete_hive_catalog( + self, + ) -> Callable[ + [hive_metastore.DeleteHiveCatalogRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + + @property + def create_hive_database( + self, + ) -> Callable[ + [hive_metastore.CreateHiveDatabaseRequest], + Union[hive_metastore.HiveDatabase, Awaitable[hive_metastore.HiveDatabase]], + ]: + raise NotImplementedError() + + @property + def get_hive_database( + self, + ) -> Callable[ + [hive_metastore.GetHiveDatabaseRequest], + Union[hive_metastore.HiveDatabase, Awaitable[hive_metastore.HiveDatabase]], + ]: + raise NotImplementedError() + + @property + def list_hive_databases( + self, + ) -> Callable[ + [hive_metastore.ListHiveDatabasesRequest], + Union[ + hive_metastore.ListHiveDatabasesResponse, + Awaitable[hive_metastore.ListHiveDatabasesResponse], + ], + ]: + raise NotImplementedError() + + @property + def update_hive_database( + self, + ) -> Callable[ + [hive_metastore.UpdateHiveDatabaseRequest], + Union[hive_metastore.HiveDatabase, Awaitable[hive_metastore.HiveDatabase]], + ]: + raise NotImplementedError() + + @property + def delete_hive_database( + self, + ) -> Callable[ + [hive_metastore.DeleteHiveDatabaseRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + + @property + def create_hive_table( + self, + ) -> Callable[ + [hive_metastore.CreateHiveTableRequest], + Union[hive_metastore.HiveTable, Awaitable[hive_metastore.HiveTable]], + ]: + raise NotImplementedError() + + @property + def get_hive_table( + self, + ) -> Callable[ + [hive_metastore.GetHiveTableRequest], + Union[hive_metastore.HiveTable, Awaitable[hive_metastore.HiveTable]], + ]: + raise NotImplementedError() + + @property + def list_hive_tables( + self, + ) -> Callable[ + [hive_metastore.ListHiveTablesRequest], + Union[ + hive_metastore.ListHiveTablesResponse, + Awaitable[hive_metastore.ListHiveTablesResponse], + ], + ]: + raise NotImplementedError() + + @property + def update_hive_table( + self, + ) -> Callable[ + [hive_metastore.UpdateHiveTableRequest], + Union[hive_metastore.HiveTable, Awaitable[hive_metastore.HiveTable]], + ]: + raise NotImplementedError() + + @property + def delete_hive_table( + self, + ) -> Callable[ + [hive_metastore.DeleteHiveTableRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + + @property + def batch_create_partitions( + self, + ) -> Callable[ + [hive_metastore.BatchCreatePartitionsRequest], + Union[ + hive_metastore.BatchCreatePartitionsResponse, + Awaitable[hive_metastore.BatchCreatePartitionsResponse], + ], + ]: + raise NotImplementedError() + + @property + def batch_delete_partitions( + self, + ) -> Callable[ + [hive_metastore.BatchDeletePartitionsRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + + @property + def batch_update_partitions( + self, + ) -> Callable[ + [hive_metastore.BatchUpdatePartitionsRequest], + Union[ + hive_metastore.BatchUpdatePartitionsResponse, + Awaitable[hive_metastore.BatchUpdatePartitionsResponse], + ], + ]: + raise NotImplementedError() + + @property + def list_partitions( + self, + ) -> Callable[ + [hive_metastore.ListPartitionsRequest], + Union[ + hive_metastore.ListPartitionsResponse, + Awaitable[hive_metastore.ListPartitionsResponse], + ], + ]: + raise NotImplementedError() + + @property + def failover_hive_catalog( + self, + ) -> Callable[ + [hive_metastore.FailoverHiveCatalogRequest], + Union[ + hive_metastore.FailoverHiveCatalogResponse, + Awaitable[hive_metastore.FailoverHiveCatalogResponse], + ], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ("HiveMetastoreServiceTransport",) diff --git a/packages/google-cloud-biglake-hive/google/cloud/biglake_hive_v1/services/hive_metastore_service/transports/grpc.py b/packages/google-cloud-biglake-hive/google/cloud/biglake_hive_v1/services/hive_metastore_service/transports/grpc.py new file mode 100644 index 000000000000..67b05f61aae3 --- /dev/null +++ b/packages/google-cloud-biglake-hive/google/cloud/biglake_hive_v1/services/hive_metastore_service/transports/grpc.py @@ -0,0 +1,903 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 json +import logging as std_logging +import pickle +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +import google.auth # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore +from google.api_core import gapic_v1, grpc_helpers +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.protobuf.json_format import MessageToJson + +from google.cloud.biglake_hive_v1.types import hive_metastore + +from .base import DEFAULT_CLIENT_INFO, HiveMetastoreServiceTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER + def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.cloud.biglake.hive.v1.HiveMetastoreService", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = response.result() + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response for {client_call_details.method}.", + extra={ + "serviceName": "google.cloud.biglake.hive.v1.HiveMetastoreService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class HiveMetastoreServiceGrpcTransport(HiveMetastoreServiceTransport): + """gRPC backend transport for HiveMetastoreService. + + Hive Metastore Service is a biglake service that allows users to + manage their external Hive catalogs. Full API compatibility with OSS + Hive Metastore APIs is not supported. The methods match the Hive + Metastore API spec mostly except for a few exceptions. These include + listing resources with pattern, environment context which are + combined in a single List API, return of ListResponse object instead + of a list of resources, transactions, locks, etc. + + The BigLake Hive Metastore API defines the following resources: + + - A collection of Google Cloud projects: ``/projects/*`` + - Each project has a collection of catalogs: ``/catalogs/*`` + - Each catalog has a collection of databases: ``/databases/*`` + - Each database has a collection of tables: ``/tables/*`` + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _stubs: Dict[str, Callable] + + def __init__( + self, + *, + host: str = "biglake.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'biglake.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientInterceptor() + self._logged_channel = grpc.intercept_channel( + self._grpc_channel, self._interceptor + ) + + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel( + cls, + host: str = "biglake.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service.""" + return self._grpc_channel + + @property + def create_hive_catalog( + self, + ) -> Callable[ + [hive_metastore.CreateHiveCatalogRequest], hive_metastore.HiveCatalog + ]: + r"""Return a callable for the create hive catalog method over gRPC. + + Creates a new hive catalog. + + Returns: + Callable[[~.CreateHiveCatalogRequest], + ~.HiveCatalog]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_hive_catalog" not in self._stubs: + self._stubs["create_hive_catalog"] = self._logged_channel.unary_unary( + "/google.cloud.biglake.hive.v1.HiveMetastoreService/CreateHiveCatalog", + request_serializer=hive_metastore.CreateHiveCatalogRequest.serialize, + response_deserializer=hive_metastore.HiveCatalog.deserialize, + ) + return self._stubs["create_hive_catalog"] + + @property + def get_hive_catalog( + self, + ) -> Callable[[hive_metastore.GetHiveCatalogRequest], hive_metastore.HiveCatalog]: + r"""Return a callable for the get hive catalog method over gRPC. + + Gets the catalog specified by the resource name. + + Returns: + Callable[[~.GetHiveCatalogRequest], + ~.HiveCatalog]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_hive_catalog" not in self._stubs: + self._stubs["get_hive_catalog"] = self._logged_channel.unary_unary( + "/google.cloud.biglake.hive.v1.HiveMetastoreService/GetHiveCatalog", + request_serializer=hive_metastore.GetHiveCatalogRequest.serialize, + response_deserializer=hive_metastore.HiveCatalog.deserialize, + ) + return self._stubs["get_hive_catalog"] + + @property + def list_hive_catalogs( + self, + ) -> Callable[ + [hive_metastore.ListHiveCatalogsRequest], + hive_metastore.ListHiveCatalogsResponse, + ]: + r"""Return a callable for the list hive catalogs method over gRPC. + + List all catalogs in a specified project. + + Returns: + Callable[[~.ListHiveCatalogsRequest], + ~.ListHiveCatalogsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_hive_catalogs" not in self._stubs: + self._stubs["list_hive_catalogs"] = self._logged_channel.unary_unary( + "/google.cloud.biglake.hive.v1.HiveMetastoreService/ListHiveCatalogs", + request_serializer=hive_metastore.ListHiveCatalogsRequest.serialize, + response_deserializer=hive_metastore.ListHiveCatalogsResponse.deserialize, + ) + return self._stubs["list_hive_catalogs"] + + @property + def update_hive_catalog( + self, + ) -> Callable[ + [hive_metastore.UpdateHiveCatalogRequest], hive_metastore.HiveCatalog + ]: + r"""Return a callable for the update hive catalog method over gRPC. + + Updates an existing catalog. + + Returns: + Callable[[~.UpdateHiveCatalogRequest], + ~.HiveCatalog]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_hive_catalog" not in self._stubs: + self._stubs["update_hive_catalog"] = self._logged_channel.unary_unary( + "/google.cloud.biglake.hive.v1.HiveMetastoreService/UpdateHiveCatalog", + request_serializer=hive_metastore.UpdateHiveCatalogRequest.serialize, + response_deserializer=hive_metastore.HiveCatalog.deserialize, + ) + return self._stubs["update_hive_catalog"] + + @property + def delete_hive_catalog( + self, + ) -> Callable[[hive_metastore.DeleteHiveCatalogRequest], empty_pb2.Empty]: + r"""Return a callable for the delete hive catalog method over gRPC. + + Deletes an existing catalog specified by the catalog + ID. Delete will fail if the catalog is not empty. + + Returns: + Callable[[~.DeleteHiveCatalogRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_hive_catalog" not in self._stubs: + self._stubs["delete_hive_catalog"] = self._logged_channel.unary_unary( + "/google.cloud.biglake.hive.v1.HiveMetastoreService/DeleteHiveCatalog", + request_serializer=hive_metastore.DeleteHiveCatalogRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_hive_catalog"] + + @property + def create_hive_database( + self, + ) -> Callable[ + [hive_metastore.CreateHiveDatabaseRequest], hive_metastore.HiveDatabase + ]: + r"""Return a callable for the create hive database method over gRPC. + + Creates a new database. + + Returns: + Callable[[~.CreateHiveDatabaseRequest], + ~.HiveDatabase]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_hive_database" not in self._stubs: + self._stubs["create_hive_database"] = self._logged_channel.unary_unary( + "/google.cloud.biglake.hive.v1.HiveMetastoreService/CreateHiveDatabase", + request_serializer=hive_metastore.CreateHiveDatabaseRequest.serialize, + response_deserializer=hive_metastore.HiveDatabase.deserialize, + ) + return self._stubs["create_hive_database"] + + @property + def get_hive_database( + self, + ) -> Callable[[hive_metastore.GetHiveDatabaseRequest], hive_metastore.HiveDatabase]: + r"""Return a callable for the get hive database method over gRPC. + + Gets the database specified by the resource name. + + Returns: + Callable[[~.GetHiveDatabaseRequest], + ~.HiveDatabase]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_hive_database" not in self._stubs: + self._stubs["get_hive_database"] = self._logged_channel.unary_unary( + "/google.cloud.biglake.hive.v1.HiveMetastoreService/GetHiveDatabase", + request_serializer=hive_metastore.GetHiveDatabaseRequest.serialize, + response_deserializer=hive_metastore.HiveDatabase.deserialize, + ) + return self._stubs["get_hive_database"] + + @property + def list_hive_databases( + self, + ) -> Callable[ + [hive_metastore.ListHiveDatabasesRequest], + hive_metastore.ListHiveDatabasesResponse, + ]: + r"""Return a callable for the list hive databases method over gRPC. + + List all databases in a specified catalog. + + Returns: + Callable[[~.ListHiveDatabasesRequest], + ~.ListHiveDatabasesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_hive_databases" not in self._stubs: + self._stubs["list_hive_databases"] = self._logged_channel.unary_unary( + "/google.cloud.biglake.hive.v1.HiveMetastoreService/ListHiveDatabases", + request_serializer=hive_metastore.ListHiveDatabasesRequest.serialize, + response_deserializer=hive_metastore.ListHiveDatabasesResponse.deserialize, + ) + return self._stubs["list_hive_databases"] + + @property + def update_hive_database( + self, + ) -> Callable[ + [hive_metastore.UpdateHiveDatabaseRequest], hive_metastore.HiveDatabase + ]: + r"""Return a callable for the update hive database method over gRPC. + + Updates an existing database specified by the + database name. + + Returns: + Callable[[~.UpdateHiveDatabaseRequest], + ~.HiveDatabase]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_hive_database" not in self._stubs: + self._stubs["update_hive_database"] = self._logged_channel.unary_unary( + "/google.cloud.biglake.hive.v1.HiveMetastoreService/UpdateHiveDatabase", + request_serializer=hive_metastore.UpdateHiveDatabaseRequest.serialize, + response_deserializer=hive_metastore.HiveDatabase.deserialize, + ) + return self._stubs["update_hive_database"] + + @property + def delete_hive_database( + self, + ) -> Callable[[hive_metastore.DeleteHiveDatabaseRequest], empty_pb2.Empty]: + r"""Return a callable for the delete hive database method over gRPC. + + Deletes an existing database specified by the + database name. + + Returns: + Callable[[~.DeleteHiveDatabaseRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_hive_database" not in self._stubs: + self._stubs["delete_hive_database"] = self._logged_channel.unary_unary( + "/google.cloud.biglake.hive.v1.HiveMetastoreService/DeleteHiveDatabase", + request_serializer=hive_metastore.DeleteHiveDatabaseRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_hive_database"] + + @property + def create_hive_table( + self, + ) -> Callable[[hive_metastore.CreateHiveTableRequest], hive_metastore.HiveTable]: + r"""Return a callable for the create hive table method over gRPC. + + Creates a new hive table. + + Returns: + Callable[[~.CreateHiveTableRequest], + ~.HiveTable]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_hive_table" not in self._stubs: + self._stubs["create_hive_table"] = self._logged_channel.unary_unary( + "/google.cloud.biglake.hive.v1.HiveMetastoreService/CreateHiveTable", + request_serializer=hive_metastore.CreateHiveTableRequest.serialize, + response_deserializer=hive_metastore.HiveTable.deserialize, + ) + return self._stubs["create_hive_table"] + + @property + def get_hive_table( + self, + ) -> Callable[[hive_metastore.GetHiveTableRequest], hive_metastore.HiveTable]: + r"""Return a callable for the get hive table method over gRPC. + + Gets the table specified by the resource name. + + Returns: + Callable[[~.GetHiveTableRequest], + ~.HiveTable]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_hive_table" not in self._stubs: + self._stubs["get_hive_table"] = self._logged_channel.unary_unary( + "/google.cloud.biglake.hive.v1.HiveMetastoreService/GetHiveTable", + request_serializer=hive_metastore.GetHiveTableRequest.serialize, + response_deserializer=hive_metastore.HiveTable.deserialize, + ) + return self._stubs["get_hive_table"] + + @property + def list_hive_tables( + self, + ) -> Callable[ + [hive_metastore.ListHiveTablesRequest], hive_metastore.ListHiveTablesResponse + ]: + r"""Return a callable for the list hive tables method over gRPC. + + List all hive tables in a specified project under the + hive catalog and database. + + Returns: + Callable[[~.ListHiveTablesRequest], + ~.ListHiveTablesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_hive_tables" not in self._stubs: + self._stubs["list_hive_tables"] = self._logged_channel.unary_unary( + "/google.cloud.biglake.hive.v1.HiveMetastoreService/ListHiveTables", + request_serializer=hive_metastore.ListHiveTablesRequest.serialize, + response_deserializer=hive_metastore.ListHiveTablesResponse.deserialize, + ) + return self._stubs["list_hive_tables"] + + @property + def update_hive_table( + self, + ) -> Callable[[hive_metastore.UpdateHiveTableRequest], hive_metastore.HiveTable]: + r"""Return a callable for the update hive table method over gRPC. + + Updates an existing table specified by the table + name. + + Returns: + Callable[[~.UpdateHiveTableRequest], + ~.HiveTable]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_hive_table" not in self._stubs: + self._stubs["update_hive_table"] = self._logged_channel.unary_unary( + "/google.cloud.biglake.hive.v1.HiveMetastoreService/UpdateHiveTable", + request_serializer=hive_metastore.UpdateHiveTableRequest.serialize, + response_deserializer=hive_metastore.HiveTable.deserialize, + ) + return self._stubs["update_hive_table"] + + @property + def delete_hive_table( + self, + ) -> Callable[[hive_metastore.DeleteHiveTableRequest], empty_pb2.Empty]: + r"""Return a callable for the delete hive table method over gRPC. + + Deletes an existing table specified by the table + name. + + Returns: + Callable[[~.DeleteHiveTableRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_hive_table" not in self._stubs: + self._stubs["delete_hive_table"] = self._logged_channel.unary_unary( + "/google.cloud.biglake.hive.v1.HiveMetastoreService/DeleteHiveTable", + request_serializer=hive_metastore.DeleteHiveTableRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_hive_table"] + + @property + def batch_create_partitions( + self, + ) -> Callable[ + [hive_metastore.BatchCreatePartitionsRequest], + hive_metastore.BatchCreatePartitionsResponse, + ]: + r"""Return a callable for the batch create partitions method over gRPC. + + Adds partitions to a table. + + Returns: + Callable[[~.BatchCreatePartitionsRequest], + ~.BatchCreatePartitionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "batch_create_partitions" not in self._stubs: + self._stubs["batch_create_partitions"] = self._logged_channel.unary_unary( + "/google.cloud.biglake.hive.v1.HiveMetastoreService/BatchCreatePartitions", + request_serializer=hive_metastore.BatchCreatePartitionsRequest.serialize, + response_deserializer=hive_metastore.BatchCreatePartitionsResponse.deserialize, + ) + return self._stubs["batch_create_partitions"] + + @property + def batch_delete_partitions( + self, + ) -> Callable[[hive_metastore.BatchDeletePartitionsRequest], empty_pb2.Empty]: + r"""Return a callable for the batch delete partitions method over gRPC. + + Deletes partitions from a table. + + Returns: + Callable[[~.BatchDeletePartitionsRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "batch_delete_partitions" not in self._stubs: + self._stubs["batch_delete_partitions"] = self._logged_channel.unary_unary( + "/google.cloud.biglake.hive.v1.HiveMetastoreService/BatchDeletePartitions", + request_serializer=hive_metastore.BatchDeletePartitionsRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["batch_delete_partitions"] + + @property + def batch_update_partitions( + self, + ) -> Callable[ + [hive_metastore.BatchUpdatePartitionsRequest], + hive_metastore.BatchUpdatePartitionsResponse, + ]: + r"""Return a callable for the batch update partitions method over gRPC. + + Updates partitions in a table. + + Returns: + Callable[[~.BatchUpdatePartitionsRequest], + ~.BatchUpdatePartitionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "batch_update_partitions" not in self._stubs: + self._stubs["batch_update_partitions"] = self._logged_channel.unary_unary( + "/google.cloud.biglake.hive.v1.HiveMetastoreService/BatchUpdatePartitions", + request_serializer=hive_metastore.BatchUpdatePartitionsRequest.serialize, + response_deserializer=hive_metastore.BatchUpdatePartitionsResponse.deserialize, + ) + return self._stubs["batch_update_partitions"] + + @property + def list_partitions( + self, + ) -> Callable[ + [hive_metastore.ListPartitionsRequest], hive_metastore.ListPartitionsResponse + ]: + r"""Return a callable for the list partitions method over gRPC. + + Streams list of partitions from a table. + + Returns: + Callable[[~.ListPartitionsRequest], + ~.ListPartitionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_partitions" not in self._stubs: + self._stubs["list_partitions"] = self._logged_channel.unary_stream( + "/google.cloud.biglake.hive.v1.HiveMetastoreService/ListPartitions", + request_serializer=hive_metastore.ListPartitionsRequest.serialize, + response_deserializer=hive_metastore.ListPartitionsResponse.deserialize, + ) + return self._stubs["list_partitions"] + + @property + def failover_hive_catalog( + self, + ) -> Callable[ + [hive_metastore.FailoverHiveCatalogRequest], + hive_metastore.FailoverHiveCatalogResponse, + ]: + r"""Return a callable for the failover hive catalog method over gRPC. + + Failover the catalog to a new primary replica region. + + Returns: + Callable[[~.FailoverHiveCatalogRequest], + ~.FailoverHiveCatalogResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "failover_hive_catalog" not in self._stubs: + self._stubs["failover_hive_catalog"] = self._logged_channel.unary_unary( + "/google.cloud.biglake.hive.v1.HiveMetastoreService/FailoverHiveCatalog", + request_serializer=hive_metastore.FailoverHiveCatalogRequest.serialize, + response_deserializer=hive_metastore.FailoverHiveCatalogResponse.deserialize, + ) + return self._stubs["failover_hive_catalog"] + + def close(self): + self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ("HiveMetastoreServiceGrpcTransport",) diff --git a/packages/google-cloud-biglake-hive/google/cloud/biglake_hive_v1/services/hive_metastore_service/transports/grpc_asyncio.py b/packages/google-cloud-biglake-hive/google/cloud/biglake_hive_v1/services/hive_metastore_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..4927a34de3ec --- /dev/null +++ b/packages/google-cloud-biglake-hive/google/cloud/biglake_hive_v1/services/hive_metastore_service/transports/grpc_asyncio.py @@ -0,0 +1,1041 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 inspect +import json +import logging as std_logging +import pickle +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, grpc_helpers_async +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.protobuf.json_format import MessageToJson +from grpc.experimental import aio # type: ignore + +from google.cloud.biglake_hive_v1.types import hive_metastore + +from .base import DEFAULT_CLIENT_INFO, HiveMetastoreServiceTransport +from .grpc import HiveMetastoreServiceGrpcTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientAIOInterceptor( + grpc.aio.UnaryUnaryClientInterceptor +): # pragma: NO COVER + async def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.cloud.biglake.hive.v1.HiveMetastoreService", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = await continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = await response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = await response + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response to rpc {client_call_details.method}.", + extra={ + "serviceName": "google.cloud.biglake.hive.v1.HiveMetastoreService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class HiveMetastoreServiceGrpcAsyncIOTransport(HiveMetastoreServiceTransport): + """gRPC AsyncIO backend transport for HiveMetastoreService. + + Hive Metastore Service is a biglake service that allows users to + manage their external Hive catalogs. Full API compatibility with OSS + Hive Metastore APIs is not supported. The methods match the Hive + Metastore API spec mostly except for a few exceptions. These include + listing resources with pattern, environment context which are + combined in a single List API, return of ListResponse object instead + of a list of resources, transactions, locks, etc. + + The BigLake Hive Metastore API defines the following resources: + + - A collection of Google Cloud projects: ``/projects/*`` + - Each project has a collection of catalogs: ``/catalogs/*`` + - Each catalog has a collection of databases: ``/databases/*`` + - Each database has a collection of tables: ``/tables/*`` + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel( + cls, + host: str = "biglake.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "biglake.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'biglake.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientAIOInterceptor() + self._grpc_channel._unary_unary_interceptors.append(self._interceptor) + self._logged_channel = self._grpc_channel + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def create_hive_catalog( + self, + ) -> Callable[ + [hive_metastore.CreateHiveCatalogRequest], Awaitable[hive_metastore.HiveCatalog] + ]: + r"""Return a callable for the create hive catalog method over gRPC. + + Creates a new hive catalog. + + Returns: + Callable[[~.CreateHiveCatalogRequest], + Awaitable[~.HiveCatalog]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_hive_catalog" not in self._stubs: + self._stubs["create_hive_catalog"] = self._logged_channel.unary_unary( + "/google.cloud.biglake.hive.v1.HiveMetastoreService/CreateHiveCatalog", + request_serializer=hive_metastore.CreateHiveCatalogRequest.serialize, + response_deserializer=hive_metastore.HiveCatalog.deserialize, + ) + return self._stubs["create_hive_catalog"] + + @property + def get_hive_catalog( + self, + ) -> Callable[ + [hive_metastore.GetHiveCatalogRequest], Awaitable[hive_metastore.HiveCatalog] + ]: + r"""Return a callable for the get hive catalog method over gRPC. + + Gets the catalog specified by the resource name. + + Returns: + Callable[[~.GetHiveCatalogRequest], + Awaitable[~.HiveCatalog]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_hive_catalog" not in self._stubs: + self._stubs["get_hive_catalog"] = self._logged_channel.unary_unary( + "/google.cloud.biglake.hive.v1.HiveMetastoreService/GetHiveCatalog", + request_serializer=hive_metastore.GetHiveCatalogRequest.serialize, + response_deserializer=hive_metastore.HiveCatalog.deserialize, + ) + return self._stubs["get_hive_catalog"] + + @property + def list_hive_catalogs( + self, + ) -> Callable[ + [hive_metastore.ListHiveCatalogsRequest], + Awaitable[hive_metastore.ListHiveCatalogsResponse], + ]: + r"""Return a callable for the list hive catalogs method over gRPC. + + List all catalogs in a specified project. + + Returns: + Callable[[~.ListHiveCatalogsRequest], + Awaitable[~.ListHiveCatalogsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_hive_catalogs" not in self._stubs: + self._stubs["list_hive_catalogs"] = self._logged_channel.unary_unary( + "/google.cloud.biglake.hive.v1.HiveMetastoreService/ListHiveCatalogs", + request_serializer=hive_metastore.ListHiveCatalogsRequest.serialize, + response_deserializer=hive_metastore.ListHiveCatalogsResponse.deserialize, + ) + return self._stubs["list_hive_catalogs"] + + @property + def update_hive_catalog( + self, + ) -> Callable[ + [hive_metastore.UpdateHiveCatalogRequest], Awaitable[hive_metastore.HiveCatalog] + ]: + r"""Return a callable for the update hive catalog method over gRPC. + + Updates an existing catalog. + + Returns: + Callable[[~.UpdateHiveCatalogRequest], + Awaitable[~.HiveCatalog]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_hive_catalog" not in self._stubs: + self._stubs["update_hive_catalog"] = self._logged_channel.unary_unary( + "/google.cloud.biglake.hive.v1.HiveMetastoreService/UpdateHiveCatalog", + request_serializer=hive_metastore.UpdateHiveCatalogRequest.serialize, + response_deserializer=hive_metastore.HiveCatalog.deserialize, + ) + return self._stubs["update_hive_catalog"] + + @property + def delete_hive_catalog( + self, + ) -> Callable[ + [hive_metastore.DeleteHiveCatalogRequest], Awaitable[empty_pb2.Empty] + ]: + r"""Return a callable for the delete hive catalog method over gRPC. + + Deletes an existing catalog specified by the catalog + ID. Delete will fail if the catalog is not empty. + + Returns: + Callable[[~.DeleteHiveCatalogRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_hive_catalog" not in self._stubs: + self._stubs["delete_hive_catalog"] = self._logged_channel.unary_unary( + "/google.cloud.biglake.hive.v1.HiveMetastoreService/DeleteHiveCatalog", + request_serializer=hive_metastore.DeleteHiveCatalogRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_hive_catalog"] + + @property + def create_hive_database( + self, + ) -> Callable[ + [hive_metastore.CreateHiveDatabaseRequest], + Awaitable[hive_metastore.HiveDatabase], + ]: + r"""Return a callable for the create hive database method over gRPC. + + Creates a new database. + + Returns: + Callable[[~.CreateHiveDatabaseRequest], + Awaitable[~.HiveDatabase]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_hive_database" not in self._stubs: + self._stubs["create_hive_database"] = self._logged_channel.unary_unary( + "/google.cloud.biglake.hive.v1.HiveMetastoreService/CreateHiveDatabase", + request_serializer=hive_metastore.CreateHiveDatabaseRequest.serialize, + response_deserializer=hive_metastore.HiveDatabase.deserialize, + ) + return self._stubs["create_hive_database"] + + @property + def get_hive_database( + self, + ) -> Callable[ + [hive_metastore.GetHiveDatabaseRequest], Awaitable[hive_metastore.HiveDatabase] + ]: + r"""Return a callable for the get hive database method over gRPC. + + Gets the database specified by the resource name. + + Returns: + Callable[[~.GetHiveDatabaseRequest], + Awaitable[~.HiveDatabase]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_hive_database" not in self._stubs: + self._stubs["get_hive_database"] = self._logged_channel.unary_unary( + "/google.cloud.biglake.hive.v1.HiveMetastoreService/GetHiveDatabase", + request_serializer=hive_metastore.GetHiveDatabaseRequest.serialize, + response_deserializer=hive_metastore.HiveDatabase.deserialize, + ) + return self._stubs["get_hive_database"] + + @property + def list_hive_databases( + self, + ) -> Callable[ + [hive_metastore.ListHiveDatabasesRequest], + Awaitable[hive_metastore.ListHiveDatabasesResponse], + ]: + r"""Return a callable for the list hive databases method over gRPC. + + List all databases in a specified catalog. + + Returns: + Callable[[~.ListHiveDatabasesRequest], + Awaitable[~.ListHiveDatabasesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_hive_databases" not in self._stubs: + self._stubs["list_hive_databases"] = self._logged_channel.unary_unary( + "/google.cloud.biglake.hive.v1.HiveMetastoreService/ListHiveDatabases", + request_serializer=hive_metastore.ListHiveDatabasesRequest.serialize, + response_deserializer=hive_metastore.ListHiveDatabasesResponse.deserialize, + ) + return self._stubs["list_hive_databases"] + + @property + def update_hive_database( + self, + ) -> Callable[ + [hive_metastore.UpdateHiveDatabaseRequest], + Awaitable[hive_metastore.HiveDatabase], + ]: + r"""Return a callable for the update hive database method over gRPC. + + Updates an existing database specified by the + database name. + + Returns: + Callable[[~.UpdateHiveDatabaseRequest], + Awaitable[~.HiveDatabase]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_hive_database" not in self._stubs: + self._stubs["update_hive_database"] = self._logged_channel.unary_unary( + "/google.cloud.biglake.hive.v1.HiveMetastoreService/UpdateHiveDatabase", + request_serializer=hive_metastore.UpdateHiveDatabaseRequest.serialize, + response_deserializer=hive_metastore.HiveDatabase.deserialize, + ) + return self._stubs["update_hive_database"] + + @property + def delete_hive_database( + self, + ) -> Callable[ + [hive_metastore.DeleteHiveDatabaseRequest], Awaitable[empty_pb2.Empty] + ]: + r"""Return a callable for the delete hive database method over gRPC. + + Deletes an existing database specified by the + database name. + + Returns: + Callable[[~.DeleteHiveDatabaseRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_hive_database" not in self._stubs: + self._stubs["delete_hive_database"] = self._logged_channel.unary_unary( + "/google.cloud.biglake.hive.v1.HiveMetastoreService/DeleteHiveDatabase", + request_serializer=hive_metastore.DeleteHiveDatabaseRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_hive_database"] + + @property + def create_hive_table( + self, + ) -> Callable[ + [hive_metastore.CreateHiveTableRequest], Awaitable[hive_metastore.HiveTable] + ]: + r"""Return a callable for the create hive table method over gRPC. + + Creates a new hive table. + + Returns: + Callable[[~.CreateHiveTableRequest], + Awaitable[~.HiveTable]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_hive_table" not in self._stubs: + self._stubs["create_hive_table"] = self._logged_channel.unary_unary( + "/google.cloud.biglake.hive.v1.HiveMetastoreService/CreateHiveTable", + request_serializer=hive_metastore.CreateHiveTableRequest.serialize, + response_deserializer=hive_metastore.HiveTable.deserialize, + ) + return self._stubs["create_hive_table"] + + @property + def get_hive_table( + self, + ) -> Callable[ + [hive_metastore.GetHiveTableRequest], Awaitable[hive_metastore.HiveTable] + ]: + r"""Return a callable for the get hive table method over gRPC. + + Gets the table specified by the resource name. + + Returns: + Callable[[~.GetHiveTableRequest], + Awaitable[~.HiveTable]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_hive_table" not in self._stubs: + self._stubs["get_hive_table"] = self._logged_channel.unary_unary( + "/google.cloud.biglake.hive.v1.HiveMetastoreService/GetHiveTable", + request_serializer=hive_metastore.GetHiveTableRequest.serialize, + response_deserializer=hive_metastore.HiveTable.deserialize, + ) + return self._stubs["get_hive_table"] + + @property + def list_hive_tables( + self, + ) -> Callable[ + [hive_metastore.ListHiveTablesRequest], + Awaitable[hive_metastore.ListHiveTablesResponse], + ]: + r"""Return a callable for the list hive tables method over gRPC. + + List all hive tables in a specified project under the + hive catalog and database. + + Returns: + Callable[[~.ListHiveTablesRequest], + Awaitable[~.ListHiveTablesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_hive_tables" not in self._stubs: + self._stubs["list_hive_tables"] = self._logged_channel.unary_unary( + "/google.cloud.biglake.hive.v1.HiveMetastoreService/ListHiveTables", + request_serializer=hive_metastore.ListHiveTablesRequest.serialize, + response_deserializer=hive_metastore.ListHiveTablesResponse.deserialize, + ) + return self._stubs["list_hive_tables"] + + @property + def update_hive_table( + self, + ) -> Callable[ + [hive_metastore.UpdateHiveTableRequest], Awaitable[hive_metastore.HiveTable] + ]: + r"""Return a callable for the update hive table method over gRPC. + + Updates an existing table specified by the table + name. + + Returns: + Callable[[~.UpdateHiveTableRequest], + Awaitable[~.HiveTable]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_hive_table" not in self._stubs: + self._stubs["update_hive_table"] = self._logged_channel.unary_unary( + "/google.cloud.biglake.hive.v1.HiveMetastoreService/UpdateHiveTable", + request_serializer=hive_metastore.UpdateHiveTableRequest.serialize, + response_deserializer=hive_metastore.HiveTable.deserialize, + ) + return self._stubs["update_hive_table"] + + @property + def delete_hive_table( + self, + ) -> Callable[[hive_metastore.DeleteHiveTableRequest], Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete hive table method over gRPC. + + Deletes an existing table specified by the table + name. + + Returns: + Callable[[~.DeleteHiveTableRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_hive_table" not in self._stubs: + self._stubs["delete_hive_table"] = self._logged_channel.unary_unary( + "/google.cloud.biglake.hive.v1.HiveMetastoreService/DeleteHiveTable", + request_serializer=hive_metastore.DeleteHiveTableRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_hive_table"] + + @property + def batch_create_partitions( + self, + ) -> Callable[ + [hive_metastore.BatchCreatePartitionsRequest], + Awaitable[hive_metastore.BatchCreatePartitionsResponse], + ]: + r"""Return a callable for the batch create partitions method over gRPC. + + Adds partitions to a table. + + Returns: + Callable[[~.BatchCreatePartitionsRequest], + Awaitable[~.BatchCreatePartitionsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "batch_create_partitions" not in self._stubs: + self._stubs["batch_create_partitions"] = self._logged_channel.unary_unary( + "/google.cloud.biglake.hive.v1.HiveMetastoreService/BatchCreatePartitions", + request_serializer=hive_metastore.BatchCreatePartitionsRequest.serialize, + response_deserializer=hive_metastore.BatchCreatePartitionsResponse.deserialize, + ) + return self._stubs["batch_create_partitions"] + + @property + def batch_delete_partitions( + self, + ) -> Callable[ + [hive_metastore.BatchDeletePartitionsRequest], Awaitable[empty_pb2.Empty] + ]: + r"""Return a callable for the batch delete partitions method over gRPC. + + Deletes partitions from a table. + + Returns: + Callable[[~.BatchDeletePartitionsRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "batch_delete_partitions" not in self._stubs: + self._stubs["batch_delete_partitions"] = self._logged_channel.unary_unary( + "/google.cloud.biglake.hive.v1.HiveMetastoreService/BatchDeletePartitions", + request_serializer=hive_metastore.BatchDeletePartitionsRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["batch_delete_partitions"] + + @property + def batch_update_partitions( + self, + ) -> Callable[ + [hive_metastore.BatchUpdatePartitionsRequest], + Awaitable[hive_metastore.BatchUpdatePartitionsResponse], + ]: + r"""Return a callable for the batch update partitions method over gRPC. + + Updates partitions in a table. + + Returns: + Callable[[~.BatchUpdatePartitionsRequest], + Awaitable[~.BatchUpdatePartitionsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "batch_update_partitions" not in self._stubs: + self._stubs["batch_update_partitions"] = self._logged_channel.unary_unary( + "/google.cloud.biglake.hive.v1.HiveMetastoreService/BatchUpdatePartitions", + request_serializer=hive_metastore.BatchUpdatePartitionsRequest.serialize, + response_deserializer=hive_metastore.BatchUpdatePartitionsResponse.deserialize, + ) + return self._stubs["batch_update_partitions"] + + @property + def list_partitions( + self, + ) -> Callable[ + [hive_metastore.ListPartitionsRequest], + Awaitable[hive_metastore.ListPartitionsResponse], + ]: + r"""Return a callable for the list partitions method over gRPC. + + Streams list of partitions from a table. + + Returns: + Callable[[~.ListPartitionsRequest], + Awaitable[~.ListPartitionsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_partitions" not in self._stubs: + self._stubs["list_partitions"] = self._logged_channel.unary_stream( + "/google.cloud.biglake.hive.v1.HiveMetastoreService/ListPartitions", + request_serializer=hive_metastore.ListPartitionsRequest.serialize, + response_deserializer=hive_metastore.ListPartitionsResponse.deserialize, + ) + return self._stubs["list_partitions"] + + @property + def failover_hive_catalog( + self, + ) -> Callable[ + [hive_metastore.FailoverHiveCatalogRequest], + Awaitable[hive_metastore.FailoverHiveCatalogResponse], + ]: + r"""Return a callable for the failover hive catalog method over gRPC. + + Failover the catalog to a new primary replica region. + + Returns: + Callable[[~.FailoverHiveCatalogRequest], + Awaitable[~.FailoverHiveCatalogResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "failover_hive_catalog" not in self._stubs: + self._stubs["failover_hive_catalog"] = self._logged_channel.unary_unary( + "/google.cloud.biglake.hive.v1.HiveMetastoreService/FailoverHiveCatalog", + request_serializer=hive_metastore.FailoverHiveCatalogRequest.serialize, + response_deserializer=hive_metastore.FailoverHiveCatalogResponse.deserialize, + ) + return self._stubs["failover_hive_catalog"] + + def _prep_wrapped_messages(self, client_info): + """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.create_hive_catalog: self._wrap_method( + self.create_hive_catalog, + default_timeout=None, + client_info=client_info, + ), + self.get_hive_catalog: self._wrap_method( + self.get_hive_catalog, + default_timeout=None, + client_info=client_info, + ), + self.list_hive_catalogs: self._wrap_method( + self.list_hive_catalogs, + default_timeout=None, + client_info=client_info, + ), + self.update_hive_catalog: self._wrap_method( + self.update_hive_catalog, + default_timeout=None, + client_info=client_info, + ), + self.delete_hive_catalog: self._wrap_method( + self.delete_hive_catalog, + default_timeout=None, + client_info=client_info, + ), + self.create_hive_database: self._wrap_method( + self.create_hive_database, + default_timeout=None, + client_info=client_info, + ), + self.get_hive_database: self._wrap_method( + self.get_hive_database, + default_timeout=None, + client_info=client_info, + ), + self.list_hive_databases: self._wrap_method( + self.list_hive_databases, + default_timeout=None, + client_info=client_info, + ), + self.update_hive_database: self._wrap_method( + self.update_hive_database, + default_timeout=None, + client_info=client_info, + ), + self.delete_hive_database: self._wrap_method( + self.delete_hive_database, + default_timeout=None, + client_info=client_info, + ), + self.create_hive_table: self._wrap_method( + self.create_hive_table, + default_timeout=None, + client_info=client_info, + ), + self.get_hive_table: self._wrap_method( + self.get_hive_table, + default_timeout=None, + client_info=client_info, + ), + self.list_hive_tables: self._wrap_method( + self.list_hive_tables, + default_timeout=None, + client_info=client_info, + ), + self.update_hive_table: self._wrap_method( + self.update_hive_table, + default_timeout=None, + client_info=client_info, + ), + self.delete_hive_table: self._wrap_method( + self.delete_hive_table, + default_timeout=None, + client_info=client_info, + ), + self.batch_create_partitions: self._wrap_method( + self.batch_create_partitions, + default_timeout=None, + client_info=client_info, + ), + self.batch_delete_partitions: self._wrap_method( + self.batch_delete_partitions, + default_timeout=None, + client_info=client_info, + ), + self.batch_update_partitions: self._wrap_method( + self.batch_update_partitions, + default_timeout=None, + client_info=client_info, + ), + self.list_partitions: self._wrap_method( + self.list_partitions, + default_timeout=None, + client_info=client_info, + ), + self.failover_hive_catalog: self._wrap_method( + self.failover_hive_catalog, + default_timeout=None, + client_info=client_info, + ), + } + + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + + def close(self): + return self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + +__all__ = ("HiveMetastoreServiceGrpcAsyncIOTransport",) diff --git a/packages/google-cloud-biglake-hive/google/cloud/biglake_hive_v1/services/hive_metastore_service/transports/rest.py b/packages/google-cloud-biglake-hive/google/cloud/biglake_hive_v1/services/hive_metastore_service/transports/rest.py new file mode 100644 index 000000000000..130f1364d3bb --- /dev/null +++ b/packages/google-cloud-biglake-hive/google/cloud/biglake_hive_v1/services/hive_metastore_service/transports/rest.py @@ -0,0 +1,4302 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 dataclasses +import json # type: ignore +import logging +import warnings +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +import google.protobuf +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, rest_helpers, rest_streaming +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.protobuf import json_format +from requests import __version__ as requests_version + +from google.cloud.biglake_hive_v1.types import hive_metastore + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseHiveMetastoreServiceRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = logging.getLogger(__name__) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=f"requests@{requests_version}", +) + +DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class HiveMetastoreServiceRestInterceptor: + """Interceptor for HiveMetastoreService. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the HiveMetastoreServiceRestTransport. + + .. code-block:: python + class MyCustomHiveMetastoreServiceInterceptor(HiveMetastoreServiceRestInterceptor): + def pre_batch_create_partitions(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_batch_create_partitions(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_batch_delete_partitions(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_batch_update_partitions(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_batch_update_partitions(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_hive_catalog(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_hive_catalog(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_hive_database(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_hive_database(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_hive_table(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_hive_table(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_hive_catalog(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_hive_database(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_hive_table(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_failover_hive_catalog(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_failover_hive_catalog(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_hive_catalog(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_hive_catalog(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_hive_database(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_hive_database(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_hive_table(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_hive_table(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_hive_catalogs(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_hive_catalogs(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_hive_databases(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_hive_databases(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_hive_tables(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_hive_tables(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_partitions(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_partitions(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_hive_catalog(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_hive_catalog(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_hive_database(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_hive_database(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_hive_table(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_hive_table(self, response): + logging.log(f"Received response: {response}") + return response + + transport = HiveMetastoreServiceRestTransport(interceptor=MyCustomHiveMetastoreServiceInterceptor()) + client = HiveMetastoreServiceClient(transport=transport) + + + """ + + def pre_batch_create_partitions( + self, + request: hive_metastore.BatchCreatePartitionsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + hive_metastore.BatchCreatePartitionsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for batch_create_partitions + + Override in a subclass to manipulate the request or metadata + before they are sent to the HiveMetastoreService server. + """ + return request, metadata + + def post_batch_create_partitions( + self, response: hive_metastore.BatchCreatePartitionsResponse + ) -> hive_metastore.BatchCreatePartitionsResponse: + """Post-rpc interceptor for batch_create_partitions + + DEPRECATED. Please use the `post_batch_create_partitions_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the HiveMetastoreService server but before + it is returned to user code. This `post_batch_create_partitions` interceptor runs + before the `post_batch_create_partitions_with_metadata` interceptor. + """ + return response + + def post_batch_create_partitions_with_metadata( + self, + response: hive_metastore.BatchCreatePartitionsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + hive_metastore.BatchCreatePartitionsResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for batch_create_partitions + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the HiveMetastoreService server but before it is returned to user code. + + We recommend only using this `post_batch_create_partitions_with_metadata` + interceptor in new development instead of the `post_batch_create_partitions` interceptor. + When both interceptors are used, this `post_batch_create_partitions_with_metadata` interceptor runs after the + `post_batch_create_partitions` interceptor. The (possibly modified) response returned by + `post_batch_create_partitions` will be passed to + `post_batch_create_partitions_with_metadata`. + """ + return response, metadata + + def pre_batch_delete_partitions( + self, + request: hive_metastore.BatchDeletePartitionsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + hive_metastore.BatchDeletePartitionsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for batch_delete_partitions + + Override in a subclass to manipulate the request or metadata + before they are sent to the HiveMetastoreService server. + """ + return request, metadata + + def pre_batch_update_partitions( + self, + request: hive_metastore.BatchUpdatePartitionsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + hive_metastore.BatchUpdatePartitionsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for batch_update_partitions + + Override in a subclass to manipulate the request or metadata + before they are sent to the HiveMetastoreService server. + """ + return request, metadata + + def post_batch_update_partitions( + self, response: hive_metastore.BatchUpdatePartitionsResponse + ) -> hive_metastore.BatchUpdatePartitionsResponse: + """Post-rpc interceptor for batch_update_partitions + + DEPRECATED. Please use the `post_batch_update_partitions_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the HiveMetastoreService server but before + it is returned to user code. This `post_batch_update_partitions` interceptor runs + before the `post_batch_update_partitions_with_metadata` interceptor. + """ + return response + + def post_batch_update_partitions_with_metadata( + self, + response: hive_metastore.BatchUpdatePartitionsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + hive_metastore.BatchUpdatePartitionsResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for batch_update_partitions + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the HiveMetastoreService server but before it is returned to user code. + + We recommend only using this `post_batch_update_partitions_with_metadata` + interceptor in new development instead of the `post_batch_update_partitions` interceptor. + When both interceptors are used, this `post_batch_update_partitions_with_metadata` interceptor runs after the + `post_batch_update_partitions` interceptor. The (possibly modified) response returned by + `post_batch_update_partitions` will be passed to + `post_batch_update_partitions_with_metadata`. + """ + return response, metadata + + def pre_create_hive_catalog( + self, + request: hive_metastore.CreateHiveCatalogRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + hive_metastore.CreateHiveCatalogRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for create_hive_catalog + + Override in a subclass to manipulate the request or metadata + before they are sent to the HiveMetastoreService server. + """ + return request, metadata + + def post_create_hive_catalog( + self, response: hive_metastore.HiveCatalog + ) -> hive_metastore.HiveCatalog: + """Post-rpc interceptor for create_hive_catalog + + DEPRECATED. Please use the `post_create_hive_catalog_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the HiveMetastoreService server but before + it is returned to user code. This `post_create_hive_catalog` interceptor runs + before the `post_create_hive_catalog_with_metadata` interceptor. + """ + return response + + def post_create_hive_catalog_with_metadata( + self, + response: hive_metastore.HiveCatalog, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[hive_metastore.HiveCatalog, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_hive_catalog + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the HiveMetastoreService server but before it is returned to user code. + + We recommend only using this `post_create_hive_catalog_with_metadata` + interceptor in new development instead of the `post_create_hive_catalog` interceptor. + When both interceptors are used, this `post_create_hive_catalog_with_metadata` interceptor runs after the + `post_create_hive_catalog` interceptor. The (possibly modified) response returned by + `post_create_hive_catalog` will be passed to + `post_create_hive_catalog_with_metadata`. + """ + return response, metadata + + def pre_create_hive_database( + self, + request: hive_metastore.CreateHiveDatabaseRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + hive_metastore.CreateHiveDatabaseRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for create_hive_database + + Override in a subclass to manipulate the request or metadata + before they are sent to the HiveMetastoreService server. + """ + return request, metadata + + def post_create_hive_database( + self, response: hive_metastore.HiveDatabase + ) -> hive_metastore.HiveDatabase: + """Post-rpc interceptor for create_hive_database + + DEPRECATED. Please use the `post_create_hive_database_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the HiveMetastoreService server but before + it is returned to user code. This `post_create_hive_database` interceptor runs + before the `post_create_hive_database_with_metadata` interceptor. + """ + return response + + def post_create_hive_database_with_metadata( + self, + response: hive_metastore.HiveDatabase, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[hive_metastore.HiveDatabase, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_hive_database + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the HiveMetastoreService server but before it is returned to user code. + + We recommend only using this `post_create_hive_database_with_metadata` + interceptor in new development instead of the `post_create_hive_database` interceptor. + When both interceptors are used, this `post_create_hive_database_with_metadata` interceptor runs after the + `post_create_hive_database` interceptor. The (possibly modified) response returned by + `post_create_hive_database` will be passed to + `post_create_hive_database_with_metadata`. + """ + return response, metadata + + def pre_create_hive_table( + self, + request: hive_metastore.CreateHiveTableRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + hive_metastore.CreateHiveTableRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for create_hive_table + + Override in a subclass to manipulate the request or metadata + before they are sent to the HiveMetastoreService server. + """ + return request, metadata + + def post_create_hive_table( + self, response: hive_metastore.HiveTable + ) -> hive_metastore.HiveTable: + """Post-rpc interceptor for create_hive_table + + DEPRECATED. Please use the `post_create_hive_table_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the HiveMetastoreService server but before + it is returned to user code. This `post_create_hive_table` interceptor runs + before the `post_create_hive_table_with_metadata` interceptor. + """ + return response + + def post_create_hive_table_with_metadata( + self, + response: hive_metastore.HiveTable, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[hive_metastore.HiveTable, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_hive_table + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the HiveMetastoreService server but before it is returned to user code. + + We recommend only using this `post_create_hive_table_with_metadata` + interceptor in new development instead of the `post_create_hive_table` interceptor. + When both interceptors are used, this `post_create_hive_table_with_metadata` interceptor runs after the + `post_create_hive_table` interceptor. The (possibly modified) response returned by + `post_create_hive_table` will be passed to + `post_create_hive_table_with_metadata`. + """ + return response, metadata + + def pre_delete_hive_catalog( + self, + request: hive_metastore.DeleteHiveCatalogRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + hive_metastore.DeleteHiveCatalogRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for delete_hive_catalog + + Override in a subclass to manipulate the request or metadata + before they are sent to the HiveMetastoreService server. + """ + return request, metadata + + def pre_delete_hive_database( + self, + request: hive_metastore.DeleteHiveDatabaseRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + hive_metastore.DeleteHiveDatabaseRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for delete_hive_database + + Override in a subclass to manipulate the request or metadata + before they are sent to the HiveMetastoreService server. + """ + return request, metadata + + def pre_delete_hive_table( + self, + request: hive_metastore.DeleteHiveTableRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + hive_metastore.DeleteHiveTableRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for delete_hive_table + + Override in a subclass to manipulate the request or metadata + before they are sent to the HiveMetastoreService server. + """ + return request, metadata + + def pre_failover_hive_catalog( + self, + request: hive_metastore.FailoverHiveCatalogRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + hive_metastore.FailoverHiveCatalogRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for failover_hive_catalog + + Override in a subclass to manipulate the request or metadata + before they are sent to the HiveMetastoreService server. + """ + return request, metadata + + def post_failover_hive_catalog( + self, response: hive_metastore.FailoverHiveCatalogResponse + ) -> hive_metastore.FailoverHiveCatalogResponse: + """Post-rpc interceptor for failover_hive_catalog + + DEPRECATED. Please use the `post_failover_hive_catalog_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the HiveMetastoreService server but before + it is returned to user code. This `post_failover_hive_catalog` interceptor runs + before the `post_failover_hive_catalog_with_metadata` interceptor. + """ + return response + + def post_failover_hive_catalog_with_metadata( + self, + response: hive_metastore.FailoverHiveCatalogResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + hive_metastore.FailoverHiveCatalogResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for failover_hive_catalog + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the HiveMetastoreService server but before it is returned to user code. + + We recommend only using this `post_failover_hive_catalog_with_metadata` + interceptor in new development instead of the `post_failover_hive_catalog` interceptor. + When both interceptors are used, this `post_failover_hive_catalog_with_metadata` interceptor runs after the + `post_failover_hive_catalog` interceptor. The (possibly modified) response returned by + `post_failover_hive_catalog` will be passed to + `post_failover_hive_catalog_with_metadata`. + """ + return response, metadata + + def pre_get_hive_catalog( + self, + request: hive_metastore.GetHiveCatalogRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + hive_metastore.GetHiveCatalogRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_hive_catalog + + Override in a subclass to manipulate the request or metadata + before they are sent to the HiveMetastoreService server. + """ + return request, metadata + + def post_get_hive_catalog( + self, response: hive_metastore.HiveCatalog + ) -> hive_metastore.HiveCatalog: + """Post-rpc interceptor for get_hive_catalog + + DEPRECATED. Please use the `post_get_hive_catalog_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the HiveMetastoreService server but before + it is returned to user code. This `post_get_hive_catalog` interceptor runs + before the `post_get_hive_catalog_with_metadata` interceptor. + """ + return response + + def post_get_hive_catalog_with_metadata( + self, + response: hive_metastore.HiveCatalog, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[hive_metastore.HiveCatalog, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_hive_catalog + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the HiveMetastoreService server but before it is returned to user code. + + We recommend only using this `post_get_hive_catalog_with_metadata` + interceptor in new development instead of the `post_get_hive_catalog` interceptor. + When both interceptors are used, this `post_get_hive_catalog_with_metadata` interceptor runs after the + `post_get_hive_catalog` interceptor. The (possibly modified) response returned by + `post_get_hive_catalog` will be passed to + `post_get_hive_catalog_with_metadata`. + """ + return response, metadata + + def pre_get_hive_database( + self, + request: hive_metastore.GetHiveDatabaseRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + hive_metastore.GetHiveDatabaseRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_hive_database + + Override in a subclass to manipulate the request or metadata + before they are sent to the HiveMetastoreService server. + """ + return request, metadata + + def post_get_hive_database( + self, response: hive_metastore.HiveDatabase + ) -> hive_metastore.HiveDatabase: + """Post-rpc interceptor for get_hive_database + + DEPRECATED. Please use the `post_get_hive_database_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the HiveMetastoreService server but before + it is returned to user code. This `post_get_hive_database` interceptor runs + before the `post_get_hive_database_with_metadata` interceptor. + """ + return response + + def post_get_hive_database_with_metadata( + self, + response: hive_metastore.HiveDatabase, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[hive_metastore.HiveDatabase, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_hive_database + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the HiveMetastoreService server but before it is returned to user code. + + We recommend only using this `post_get_hive_database_with_metadata` + interceptor in new development instead of the `post_get_hive_database` interceptor. + When both interceptors are used, this `post_get_hive_database_with_metadata` interceptor runs after the + `post_get_hive_database` interceptor. The (possibly modified) response returned by + `post_get_hive_database` will be passed to + `post_get_hive_database_with_metadata`. + """ + return response, metadata + + def pre_get_hive_table( + self, + request: hive_metastore.GetHiveTableRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + hive_metastore.GetHiveTableRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_hive_table + + Override in a subclass to manipulate the request or metadata + before they are sent to the HiveMetastoreService server. + """ + return request, metadata + + def post_get_hive_table( + self, response: hive_metastore.HiveTable + ) -> hive_metastore.HiveTable: + """Post-rpc interceptor for get_hive_table + + DEPRECATED. Please use the `post_get_hive_table_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the HiveMetastoreService server but before + it is returned to user code. This `post_get_hive_table` interceptor runs + before the `post_get_hive_table_with_metadata` interceptor. + """ + return response + + def post_get_hive_table_with_metadata( + self, + response: hive_metastore.HiveTable, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[hive_metastore.HiveTable, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_hive_table + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the HiveMetastoreService server but before it is returned to user code. + + We recommend only using this `post_get_hive_table_with_metadata` + interceptor in new development instead of the `post_get_hive_table` interceptor. + When both interceptors are used, this `post_get_hive_table_with_metadata` interceptor runs after the + `post_get_hive_table` interceptor. The (possibly modified) response returned by + `post_get_hive_table` will be passed to + `post_get_hive_table_with_metadata`. + """ + return response, metadata + + def pre_list_hive_catalogs( + self, + request: hive_metastore.ListHiveCatalogsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + hive_metastore.ListHiveCatalogsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_hive_catalogs + + Override in a subclass to manipulate the request or metadata + before they are sent to the HiveMetastoreService server. + """ + return request, metadata + + def post_list_hive_catalogs( + self, response: hive_metastore.ListHiveCatalogsResponse + ) -> hive_metastore.ListHiveCatalogsResponse: + """Post-rpc interceptor for list_hive_catalogs + + DEPRECATED. Please use the `post_list_hive_catalogs_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the HiveMetastoreService server but before + it is returned to user code. This `post_list_hive_catalogs` interceptor runs + before the `post_list_hive_catalogs_with_metadata` interceptor. + """ + return response + + def post_list_hive_catalogs_with_metadata( + self, + response: hive_metastore.ListHiveCatalogsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + hive_metastore.ListHiveCatalogsResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for list_hive_catalogs + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the HiveMetastoreService server but before it is returned to user code. + + We recommend only using this `post_list_hive_catalogs_with_metadata` + interceptor in new development instead of the `post_list_hive_catalogs` interceptor. + When both interceptors are used, this `post_list_hive_catalogs_with_metadata` interceptor runs after the + `post_list_hive_catalogs` interceptor. The (possibly modified) response returned by + `post_list_hive_catalogs` will be passed to + `post_list_hive_catalogs_with_metadata`. + """ + return response, metadata + + def pre_list_hive_databases( + self, + request: hive_metastore.ListHiveDatabasesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + hive_metastore.ListHiveDatabasesRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_hive_databases + + Override in a subclass to manipulate the request or metadata + before they are sent to the HiveMetastoreService server. + """ + return request, metadata + + def post_list_hive_databases( + self, response: hive_metastore.ListHiveDatabasesResponse + ) -> hive_metastore.ListHiveDatabasesResponse: + """Post-rpc interceptor for list_hive_databases + + DEPRECATED. Please use the `post_list_hive_databases_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the HiveMetastoreService server but before + it is returned to user code. This `post_list_hive_databases` interceptor runs + before the `post_list_hive_databases_with_metadata` interceptor. + """ + return response + + def post_list_hive_databases_with_metadata( + self, + response: hive_metastore.ListHiveDatabasesResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + hive_metastore.ListHiveDatabasesResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for list_hive_databases + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the HiveMetastoreService server but before it is returned to user code. + + We recommend only using this `post_list_hive_databases_with_metadata` + interceptor in new development instead of the `post_list_hive_databases` interceptor. + When both interceptors are used, this `post_list_hive_databases_with_metadata` interceptor runs after the + `post_list_hive_databases` interceptor. The (possibly modified) response returned by + `post_list_hive_databases` will be passed to + `post_list_hive_databases_with_metadata`. + """ + return response, metadata + + def pre_list_hive_tables( + self, + request: hive_metastore.ListHiveTablesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + hive_metastore.ListHiveTablesRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_hive_tables + + Override in a subclass to manipulate the request or metadata + before they are sent to the HiveMetastoreService server. + """ + return request, metadata + + def post_list_hive_tables( + self, response: hive_metastore.ListHiveTablesResponse + ) -> hive_metastore.ListHiveTablesResponse: + """Post-rpc interceptor for list_hive_tables + + DEPRECATED. Please use the `post_list_hive_tables_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the HiveMetastoreService server but before + it is returned to user code. This `post_list_hive_tables` interceptor runs + before the `post_list_hive_tables_with_metadata` interceptor. + """ + return response + + def post_list_hive_tables_with_metadata( + self, + response: hive_metastore.ListHiveTablesResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + hive_metastore.ListHiveTablesResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for list_hive_tables + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the HiveMetastoreService server but before it is returned to user code. + + We recommend only using this `post_list_hive_tables_with_metadata` + interceptor in new development instead of the `post_list_hive_tables` interceptor. + When both interceptors are used, this `post_list_hive_tables_with_metadata` interceptor runs after the + `post_list_hive_tables` interceptor. The (possibly modified) response returned by + `post_list_hive_tables` will be passed to + `post_list_hive_tables_with_metadata`. + """ + return response, metadata + + def pre_list_partitions( + self, + request: hive_metastore.ListPartitionsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + hive_metastore.ListPartitionsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_partitions + + Override in a subclass to manipulate the request or metadata + before they are sent to the HiveMetastoreService server. + """ + return request, metadata + + def post_list_partitions( + self, response: rest_streaming.ResponseIterator + ) -> rest_streaming.ResponseIterator: + """Post-rpc interceptor for list_partitions + + DEPRECATED. Please use the `post_list_partitions_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the HiveMetastoreService server but before + it is returned to user code. This `post_list_partitions` interceptor runs + before the `post_list_partitions_with_metadata` interceptor. + """ + return response + + def post_list_partitions_with_metadata( + self, + response: rest_streaming.ResponseIterator, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + rest_streaming.ResponseIterator, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for list_partitions + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the HiveMetastoreService server but before it is returned to user code. + + We recommend only using this `post_list_partitions_with_metadata` + interceptor in new development instead of the `post_list_partitions` interceptor. + When both interceptors are used, this `post_list_partitions_with_metadata` interceptor runs after the + `post_list_partitions` interceptor. The (possibly modified) response returned by + `post_list_partitions` will be passed to + `post_list_partitions_with_metadata`. + """ + return response, metadata + + def pre_update_hive_catalog( + self, + request: hive_metastore.UpdateHiveCatalogRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + hive_metastore.UpdateHiveCatalogRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for update_hive_catalog + + Override in a subclass to manipulate the request or metadata + before they are sent to the HiveMetastoreService server. + """ + return request, metadata + + def post_update_hive_catalog( + self, response: hive_metastore.HiveCatalog + ) -> hive_metastore.HiveCatalog: + """Post-rpc interceptor for update_hive_catalog + + DEPRECATED. Please use the `post_update_hive_catalog_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the HiveMetastoreService server but before + it is returned to user code. This `post_update_hive_catalog` interceptor runs + before the `post_update_hive_catalog_with_metadata` interceptor. + """ + return response + + def post_update_hive_catalog_with_metadata( + self, + response: hive_metastore.HiveCatalog, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[hive_metastore.HiveCatalog, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_hive_catalog + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the HiveMetastoreService server but before it is returned to user code. + + We recommend only using this `post_update_hive_catalog_with_metadata` + interceptor in new development instead of the `post_update_hive_catalog` interceptor. + When both interceptors are used, this `post_update_hive_catalog_with_metadata` interceptor runs after the + `post_update_hive_catalog` interceptor. The (possibly modified) response returned by + `post_update_hive_catalog` will be passed to + `post_update_hive_catalog_with_metadata`. + """ + return response, metadata + + def pre_update_hive_database( + self, + request: hive_metastore.UpdateHiveDatabaseRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + hive_metastore.UpdateHiveDatabaseRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for update_hive_database + + Override in a subclass to manipulate the request or metadata + before they are sent to the HiveMetastoreService server. + """ + return request, metadata + + def post_update_hive_database( + self, response: hive_metastore.HiveDatabase + ) -> hive_metastore.HiveDatabase: + """Post-rpc interceptor for update_hive_database + + DEPRECATED. Please use the `post_update_hive_database_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the HiveMetastoreService server but before + it is returned to user code. This `post_update_hive_database` interceptor runs + before the `post_update_hive_database_with_metadata` interceptor. + """ + return response + + def post_update_hive_database_with_metadata( + self, + response: hive_metastore.HiveDatabase, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[hive_metastore.HiveDatabase, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_hive_database + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the HiveMetastoreService server but before it is returned to user code. + + We recommend only using this `post_update_hive_database_with_metadata` + interceptor in new development instead of the `post_update_hive_database` interceptor. + When both interceptors are used, this `post_update_hive_database_with_metadata` interceptor runs after the + `post_update_hive_database` interceptor. The (possibly modified) response returned by + `post_update_hive_database` will be passed to + `post_update_hive_database_with_metadata`. + """ + return response, metadata + + def pre_update_hive_table( + self, + request: hive_metastore.UpdateHiveTableRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + hive_metastore.UpdateHiveTableRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for update_hive_table + + Override in a subclass to manipulate the request or metadata + before they are sent to the HiveMetastoreService server. + """ + return request, metadata + + def post_update_hive_table( + self, response: hive_metastore.HiveTable + ) -> hive_metastore.HiveTable: + """Post-rpc interceptor for update_hive_table + + DEPRECATED. Please use the `post_update_hive_table_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the HiveMetastoreService server but before + it is returned to user code. This `post_update_hive_table` interceptor runs + before the `post_update_hive_table_with_metadata` interceptor. + """ + return response + + def post_update_hive_table_with_metadata( + self, + response: hive_metastore.HiveTable, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[hive_metastore.HiveTable, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_hive_table + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the HiveMetastoreService server but before it is returned to user code. + + We recommend only using this `post_update_hive_table_with_metadata` + interceptor in new development instead of the `post_update_hive_table` interceptor. + When both interceptors are used, this `post_update_hive_table_with_metadata` interceptor runs after the + `post_update_hive_table` interceptor. The (possibly modified) response returned by + `post_update_hive_table` will be passed to + `post_update_hive_table_with_metadata`. + """ + return response, metadata + + +@dataclasses.dataclass +class HiveMetastoreServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: HiveMetastoreServiceRestInterceptor + + +class HiveMetastoreServiceRestTransport(_BaseHiveMetastoreServiceRestTransport): + """REST backend synchronous transport for HiveMetastoreService. + + Hive Metastore Service is a biglake service that allows users to + manage their external Hive catalogs. Full API compatibility with OSS + Hive Metastore APIs is not supported. The methods match the Hive + Metastore API spec mostly except for a few exceptions. These include + listing resources with pattern, environment context which are + combined in a single List API, return of ListResponse object instead + of a list of resources, transactions, locks, etc. + + The BigLake Hive Metastore API defines the following resources: + + - A collection of Google Cloud projects: ``/projects/*`` + - Each project has a collection of catalogs: ``/catalogs/*`` + - Each catalog has a collection of databases: ``/databases/*`` + - Each database has a collection of tables: ``/tables/*`` + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "biglake.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[HiveMetastoreServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'biglake.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. This argument will be + removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + interceptor (Optional[HiveMetastoreServiceRestInterceptor]): Interceptor used + to manipulate requests, request metadata, and responses. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + url_scheme=url_scheme, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or HiveMetastoreServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _BatchCreatePartitions( + _BaseHiveMetastoreServiceRestTransport._BaseBatchCreatePartitions, + HiveMetastoreServiceRestStub, + ): + def __hash__(self): + return hash("HiveMetastoreServiceRestTransport.BatchCreatePartitions") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: hive_metastore.BatchCreatePartitionsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> hive_metastore.BatchCreatePartitionsResponse: + r"""Call the batch create partitions method over HTTP. + + Args: + request (~.hive_metastore.BatchCreatePartitionsRequest): + The request object. Request message for the + BatchCreatePartitions method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.hive_metastore.BatchCreatePartitionsResponse: + Response message for + BatchCreatePartitions. + + """ + + http_options = _BaseHiveMetastoreServiceRestTransport._BaseBatchCreatePartitions._get_http_options() + + request, metadata = self._interceptor.pre_batch_create_partitions( + request, metadata + ) + transcoded_request = _BaseHiveMetastoreServiceRestTransport._BaseBatchCreatePartitions._get_transcoded_request( + http_options, request + ) + + body = _BaseHiveMetastoreServiceRestTransport._BaseBatchCreatePartitions._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseHiveMetastoreServiceRestTransport._BaseBatchCreatePartitions._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.biglake.hive_v1.HiveMetastoreServiceClient.BatchCreatePartitions", + extra={ + "serviceName": "google.cloud.biglake.hive.v1.HiveMetastoreService", + "rpcName": "BatchCreatePartitions", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + HiveMetastoreServiceRestTransport._BatchCreatePartitions._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = hive_metastore.BatchCreatePartitionsResponse() + pb_resp = hive_metastore.BatchCreatePartitionsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_batch_create_partitions(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_batch_create_partitions_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + hive_metastore.BatchCreatePartitionsResponse.to_json(response) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.biglake.hive_v1.HiveMetastoreServiceClient.batch_create_partitions", + extra={ + "serviceName": "google.cloud.biglake.hive.v1.HiveMetastoreService", + "rpcName": "BatchCreatePartitions", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _BatchDeletePartitions( + _BaseHiveMetastoreServiceRestTransport._BaseBatchDeletePartitions, + HiveMetastoreServiceRestStub, + ): + def __hash__(self): + return hash("HiveMetastoreServiceRestTransport.BatchDeletePartitions") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: hive_metastore.BatchDeletePartitionsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + r"""Call the batch delete partitions method over HTTP. + + Args: + request (~.hive_metastore.BatchDeletePartitionsRequest): + The request object. Request message for + BatchDeletePartitions. The Partition is + uniquely identified by values, which is + an ordered list. Hence, there is no + separate name or partition id field. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = _BaseHiveMetastoreServiceRestTransport._BaseBatchDeletePartitions._get_http_options() + + request, metadata = self._interceptor.pre_batch_delete_partitions( + request, metadata + ) + transcoded_request = _BaseHiveMetastoreServiceRestTransport._BaseBatchDeletePartitions._get_transcoded_request( + http_options, request + ) + + body = _BaseHiveMetastoreServiceRestTransport._BaseBatchDeletePartitions._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseHiveMetastoreServiceRestTransport._BaseBatchDeletePartitions._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.biglake.hive_v1.HiveMetastoreServiceClient.BatchDeletePartitions", + extra={ + "serviceName": "google.cloud.biglake.hive.v1.HiveMetastoreService", + "rpcName": "BatchDeletePartitions", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + HiveMetastoreServiceRestTransport._BatchDeletePartitions._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _BatchUpdatePartitions( + _BaseHiveMetastoreServiceRestTransport._BaseBatchUpdatePartitions, + HiveMetastoreServiceRestStub, + ): + def __hash__(self): + return hash("HiveMetastoreServiceRestTransport.BatchUpdatePartitions") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: hive_metastore.BatchUpdatePartitionsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> hive_metastore.BatchUpdatePartitionsResponse: + r"""Call the batch update partitions method over HTTP. + + Args: + request (~.hive_metastore.BatchUpdatePartitionsRequest): + The request object. Request message for + BatchUpdatePartitions. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.hive_metastore.BatchUpdatePartitionsResponse: + Response message for + BatchUpdatePartitions. + + """ + + http_options = _BaseHiveMetastoreServiceRestTransport._BaseBatchUpdatePartitions._get_http_options() + + request, metadata = self._interceptor.pre_batch_update_partitions( + request, metadata + ) + transcoded_request = _BaseHiveMetastoreServiceRestTransport._BaseBatchUpdatePartitions._get_transcoded_request( + http_options, request + ) + + body = _BaseHiveMetastoreServiceRestTransport._BaseBatchUpdatePartitions._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseHiveMetastoreServiceRestTransport._BaseBatchUpdatePartitions._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.biglake.hive_v1.HiveMetastoreServiceClient.BatchUpdatePartitions", + extra={ + "serviceName": "google.cloud.biglake.hive.v1.HiveMetastoreService", + "rpcName": "BatchUpdatePartitions", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + HiveMetastoreServiceRestTransport._BatchUpdatePartitions._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = hive_metastore.BatchUpdatePartitionsResponse() + pb_resp = hive_metastore.BatchUpdatePartitionsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_batch_update_partitions(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_batch_update_partitions_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + hive_metastore.BatchUpdatePartitionsResponse.to_json(response) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.biglake.hive_v1.HiveMetastoreServiceClient.batch_update_partitions", + extra={ + "serviceName": "google.cloud.biglake.hive.v1.HiveMetastoreService", + "rpcName": "BatchUpdatePartitions", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateHiveCatalog( + _BaseHiveMetastoreServiceRestTransport._BaseCreateHiveCatalog, + HiveMetastoreServiceRestStub, + ): + def __hash__(self): + return hash("HiveMetastoreServiceRestTransport.CreateHiveCatalog") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: hive_metastore.CreateHiveCatalogRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> hive_metastore.HiveCatalog: + r"""Call the create hive catalog method over HTTP. + + Args: + request (~.hive_metastore.CreateHiveCatalogRequest): + The request object. Request message for the + CreateHiveCatalog method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.hive_metastore.HiveCatalog: + The HiveCatalog contains spark/hive + databases and tables in the BigLake + Metastore. While creating resources + under a catalog, ideally ensure that the + storage bucket location, spark / hive + engine location or any other compute + location match. Catalog can be viewed + as the destination for migrating an + on-prem Hive metastore to GCP. + + """ + + http_options = _BaseHiveMetastoreServiceRestTransport._BaseCreateHiveCatalog._get_http_options() + + request, metadata = self._interceptor.pre_create_hive_catalog( + request, metadata + ) + transcoded_request = _BaseHiveMetastoreServiceRestTransport._BaseCreateHiveCatalog._get_transcoded_request( + http_options, request + ) + + body = _BaseHiveMetastoreServiceRestTransport._BaseCreateHiveCatalog._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseHiveMetastoreServiceRestTransport._BaseCreateHiveCatalog._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.biglake.hive_v1.HiveMetastoreServiceClient.CreateHiveCatalog", + extra={ + "serviceName": "google.cloud.biglake.hive.v1.HiveMetastoreService", + "rpcName": "CreateHiveCatalog", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + HiveMetastoreServiceRestTransport._CreateHiveCatalog._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = hive_metastore.HiveCatalog() + pb_resp = hive_metastore.HiveCatalog.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_hive_catalog(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_hive_catalog_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = hive_metastore.HiveCatalog.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.biglake.hive_v1.HiveMetastoreServiceClient.create_hive_catalog", + extra={ + "serviceName": "google.cloud.biglake.hive.v1.HiveMetastoreService", + "rpcName": "CreateHiveCatalog", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateHiveDatabase( + _BaseHiveMetastoreServiceRestTransport._BaseCreateHiveDatabase, + HiveMetastoreServiceRestStub, + ): + def __hash__(self): + return hash("HiveMetastoreServiceRestTransport.CreateHiveDatabase") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: hive_metastore.CreateHiveDatabaseRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> hive_metastore.HiveDatabase: + r"""Call the create hive database method over HTTP. + + Args: + request (~.hive_metastore.CreateHiveDatabaseRequest): + The request object. Request message for the + CreateHiveDatabase method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.hive_metastore.HiveDatabase: + Stores the hive database information. + It includes the database name, + description, location and properties + associated with the database. + + """ + + http_options = _BaseHiveMetastoreServiceRestTransport._BaseCreateHiveDatabase._get_http_options() + + request, metadata = self._interceptor.pre_create_hive_database( + request, metadata + ) + transcoded_request = _BaseHiveMetastoreServiceRestTransport._BaseCreateHiveDatabase._get_transcoded_request( + http_options, request + ) + + body = _BaseHiveMetastoreServiceRestTransport._BaseCreateHiveDatabase._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseHiveMetastoreServiceRestTransport._BaseCreateHiveDatabase._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.biglake.hive_v1.HiveMetastoreServiceClient.CreateHiveDatabase", + extra={ + "serviceName": "google.cloud.biglake.hive.v1.HiveMetastoreService", + "rpcName": "CreateHiveDatabase", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + HiveMetastoreServiceRestTransport._CreateHiveDatabase._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = hive_metastore.HiveDatabase() + pb_resp = hive_metastore.HiveDatabase.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_hive_database(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_hive_database_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = hive_metastore.HiveDatabase.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.biglake.hive_v1.HiveMetastoreServiceClient.create_hive_database", + extra={ + "serviceName": "google.cloud.biglake.hive.v1.HiveMetastoreService", + "rpcName": "CreateHiveDatabase", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateHiveTable( + _BaseHiveMetastoreServiceRestTransport._BaseCreateHiveTable, + HiveMetastoreServiceRestStub, + ): + def __hash__(self): + return hash("HiveMetastoreServiceRestTransport.CreateHiveTable") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: hive_metastore.CreateHiveTableRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> hive_metastore.HiveTable: + r"""Call the create hive table method over HTTP. + + Args: + request (~.hive_metastore.CreateHiveTableRequest): + The request object. Request message for the + CreateHiveTable method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.hive_metastore.HiveTable: + Stores the hive table information. It + includes the table name, schema (column + names and types), data location, storage + format, serde info, etc. This message + closely matches the Table object in the + IMetastoreClient + + """ + + http_options = _BaseHiveMetastoreServiceRestTransport._BaseCreateHiveTable._get_http_options() + + request, metadata = self._interceptor.pre_create_hive_table( + request, metadata + ) + transcoded_request = _BaseHiveMetastoreServiceRestTransport._BaseCreateHiveTable._get_transcoded_request( + http_options, request + ) + + body = _BaseHiveMetastoreServiceRestTransport._BaseCreateHiveTable._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseHiveMetastoreServiceRestTransport._BaseCreateHiveTable._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.biglake.hive_v1.HiveMetastoreServiceClient.CreateHiveTable", + extra={ + "serviceName": "google.cloud.biglake.hive.v1.HiveMetastoreService", + "rpcName": "CreateHiveTable", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = HiveMetastoreServiceRestTransport._CreateHiveTable._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = hive_metastore.HiveTable() + pb_resp = hive_metastore.HiveTable.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_hive_table(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_hive_table_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = hive_metastore.HiveTable.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.biglake.hive_v1.HiveMetastoreServiceClient.create_hive_table", + extra={ + "serviceName": "google.cloud.biglake.hive.v1.HiveMetastoreService", + "rpcName": "CreateHiveTable", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteHiveCatalog( + _BaseHiveMetastoreServiceRestTransport._BaseDeleteHiveCatalog, + HiveMetastoreServiceRestStub, + ): + def __hash__(self): + return hash("HiveMetastoreServiceRestTransport.DeleteHiveCatalog") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: hive_metastore.DeleteHiveCatalogRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + r"""Call the delete hive catalog method over HTTP. + + Args: + request (~.hive_metastore.DeleteHiveCatalogRequest): + The request object. Request message for the + DeleteHiveCatalog method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = _BaseHiveMetastoreServiceRestTransport._BaseDeleteHiveCatalog._get_http_options() + + request, metadata = self._interceptor.pre_delete_hive_catalog( + request, metadata + ) + transcoded_request = _BaseHiveMetastoreServiceRestTransport._BaseDeleteHiveCatalog._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseHiveMetastoreServiceRestTransport._BaseDeleteHiveCatalog._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.biglake.hive_v1.HiveMetastoreServiceClient.DeleteHiveCatalog", + extra={ + "serviceName": "google.cloud.biglake.hive.v1.HiveMetastoreService", + "rpcName": "DeleteHiveCatalog", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + HiveMetastoreServiceRestTransport._DeleteHiveCatalog._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _DeleteHiveDatabase( + _BaseHiveMetastoreServiceRestTransport._BaseDeleteHiveDatabase, + HiveMetastoreServiceRestStub, + ): + def __hash__(self): + return hash("HiveMetastoreServiceRestTransport.DeleteHiveDatabase") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: hive_metastore.DeleteHiveDatabaseRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + r"""Call the delete hive database method over HTTP. + + Args: + request (~.hive_metastore.DeleteHiveDatabaseRequest): + The request object. Request message for the + DeleteHiveDatabase method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = _BaseHiveMetastoreServiceRestTransport._BaseDeleteHiveDatabase._get_http_options() + + request, metadata = self._interceptor.pre_delete_hive_database( + request, metadata + ) + transcoded_request = _BaseHiveMetastoreServiceRestTransport._BaseDeleteHiveDatabase._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseHiveMetastoreServiceRestTransport._BaseDeleteHiveDatabase._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.biglake.hive_v1.HiveMetastoreServiceClient.DeleteHiveDatabase", + extra={ + "serviceName": "google.cloud.biglake.hive.v1.HiveMetastoreService", + "rpcName": "DeleteHiveDatabase", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + HiveMetastoreServiceRestTransport._DeleteHiveDatabase._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _DeleteHiveTable( + _BaseHiveMetastoreServiceRestTransport._BaseDeleteHiveTable, + HiveMetastoreServiceRestStub, + ): + def __hash__(self): + return hash("HiveMetastoreServiceRestTransport.DeleteHiveTable") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: hive_metastore.DeleteHiveTableRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + r"""Call the delete hive table method over HTTP. + + Args: + request (~.hive_metastore.DeleteHiveTableRequest): + The request object. Request message for the + DeleteHiveTable method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = _BaseHiveMetastoreServiceRestTransport._BaseDeleteHiveTable._get_http_options() + + request, metadata = self._interceptor.pre_delete_hive_table( + request, metadata + ) + transcoded_request = _BaseHiveMetastoreServiceRestTransport._BaseDeleteHiveTable._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseHiveMetastoreServiceRestTransport._BaseDeleteHiveTable._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.biglake.hive_v1.HiveMetastoreServiceClient.DeleteHiveTable", + extra={ + "serviceName": "google.cloud.biglake.hive.v1.HiveMetastoreService", + "rpcName": "DeleteHiveTable", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = HiveMetastoreServiceRestTransport._DeleteHiveTable._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _FailoverHiveCatalog( + _BaseHiveMetastoreServiceRestTransport._BaseFailoverHiveCatalog, + HiveMetastoreServiceRestStub, + ): + def __hash__(self): + return hash("HiveMetastoreServiceRestTransport.FailoverHiveCatalog") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: hive_metastore.FailoverHiveCatalogRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> hive_metastore.FailoverHiveCatalogResponse: + r"""Call the failover hive catalog method over HTTP. + + Args: + request (~.hive_metastore.FailoverHiveCatalogRequest): + The request object. Request message for + FailoverHiveCatalog. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.hive_metastore.FailoverHiveCatalogResponse: + Response message for + FailoverHiveCatalog. + + """ + + http_options = _BaseHiveMetastoreServiceRestTransport._BaseFailoverHiveCatalog._get_http_options() + + request, metadata = self._interceptor.pre_failover_hive_catalog( + request, metadata + ) + transcoded_request = _BaseHiveMetastoreServiceRestTransport._BaseFailoverHiveCatalog._get_transcoded_request( + http_options, request + ) + + body = _BaseHiveMetastoreServiceRestTransport._BaseFailoverHiveCatalog._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseHiveMetastoreServiceRestTransport._BaseFailoverHiveCatalog._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.biglake.hive_v1.HiveMetastoreServiceClient.FailoverHiveCatalog", + extra={ + "serviceName": "google.cloud.biglake.hive.v1.HiveMetastoreService", + "rpcName": "FailoverHiveCatalog", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + HiveMetastoreServiceRestTransport._FailoverHiveCatalog._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = hive_metastore.FailoverHiveCatalogResponse() + pb_resp = hive_metastore.FailoverHiveCatalogResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_failover_hive_catalog(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_failover_hive_catalog_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + hive_metastore.FailoverHiveCatalogResponse.to_json(response) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.biglake.hive_v1.HiveMetastoreServiceClient.failover_hive_catalog", + extra={ + "serviceName": "google.cloud.biglake.hive.v1.HiveMetastoreService", + "rpcName": "FailoverHiveCatalog", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetHiveCatalog( + _BaseHiveMetastoreServiceRestTransport._BaseGetHiveCatalog, + HiveMetastoreServiceRestStub, + ): + def __hash__(self): + return hash("HiveMetastoreServiceRestTransport.GetHiveCatalog") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: hive_metastore.GetHiveCatalogRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> hive_metastore.HiveCatalog: + r"""Call the get hive catalog method over HTTP. + + Args: + request (~.hive_metastore.GetHiveCatalogRequest): + The request object. Request message for the + GetHiveCatalog method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.hive_metastore.HiveCatalog: + The HiveCatalog contains spark/hive + databases and tables in the BigLake + Metastore. While creating resources + under a catalog, ideally ensure that the + storage bucket location, spark / hive + engine location or any other compute + location match. Catalog can be viewed + as the destination for migrating an + on-prem Hive metastore to GCP. + + """ + + http_options = _BaseHiveMetastoreServiceRestTransport._BaseGetHiveCatalog._get_http_options() + + request, metadata = self._interceptor.pre_get_hive_catalog( + request, metadata + ) + transcoded_request = _BaseHiveMetastoreServiceRestTransport._BaseGetHiveCatalog._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseHiveMetastoreServiceRestTransport._BaseGetHiveCatalog._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.biglake.hive_v1.HiveMetastoreServiceClient.GetHiveCatalog", + extra={ + "serviceName": "google.cloud.biglake.hive.v1.HiveMetastoreService", + "rpcName": "GetHiveCatalog", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = HiveMetastoreServiceRestTransport._GetHiveCatalog._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = hive_metastore.HiveCatalog() + pb_resp = hive_metastore.HiveCatalog.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_hive_catalog(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_hive_catalog_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = hive_metastore.HiveCatalog.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.biglake.hive_v1.HiveMetastoreServiceClient.get_hive_catalog", + extra={ + "serviceName": "google.cloud.biglake.hive.v1.HiveMetastoreService", + "rpcName": "GetHiveCatalog", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetHiveDatabase( + _BaseHiveMetastoreServiceRestTransport._BaseGetHiveDatabase, + HiveMetastoreServiceRestStub, + ): + def __hash__(self): + return hash("HiveMetastoreServiceRestTransport.GetHiveDatabase") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: hive_metastore.GetHiveDatabaseRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> hive_metastore.HiveDatabase: + r"""Call the get hive database method over HTTP. + + Args: + request (~.hive_metastore.GetHiveDatabaseRequest): + The request object. Request message for the + GetHiveDatabase method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.hive_metastore.HiveDatabase: + Stores the hive database information. + It includes the database name, + description, location and properties + associated with the database. + + """ + + http_options = _BaseHiveMetastoreServiceRestTransport._BaseGetHiveDatabase._get_http_options() + + request, metadata = self._interceptor.pre_get_hive_database( + request, metadata + ) + transcoded_request = _BaseHiveMetastoreServiceRestTransport._BaseGetHiveDatabase._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseHiveMetastoreServiceRestTransport._BaseGetHiveDatabase._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.biglake.hive_v1.HiveMetastoreServiceClient.GetHiveDatabase", + extra={ + "serviceName": "google.cloud.biglake.hive.v1.HiveMetastoreService", + "rpcName": "GetHiveDatabase", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = HiveMetastoreServiceRestTransport._GetHiveDatabase._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = hive_metastore.HiveDatabase() + pb_resp = hive_metastore.HiveDatabase.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_hive_database(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_hive_database_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = hive_metastore.HiveDatabase.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.biglake.hive_v1.HiveMetastoreServiceClient.get_hive_database", + extra={ + "serviceName": "google.cloud.biglake.hive.v1.HiveMetastoreService", + "rpcName": "GetHiveDatabase", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetHiveTable( + _BaseHiveMetastoreServiceRestTransport._BaseGetHiveTable, + HiveMetastoreServiceRestStub, + ): + def __hash__(self): + return hash("HiveMetastoreServiceRestTransport.GetHiveTable") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: hive_metastore.GetHiveTableRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> hive_metastore.HiveTable: + r"""Call the get hive table method over HTTP. + + Args: + request (~.hive_metastore.GetHiveTableRequest): + The request object. Request message for the GetHiveTable + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.hive_metastore.HiveTable: + Stores the hive table information. It + includes the table name, schema (column + names and types), data location, storage + format, serde info, etc. This message + closely matches the Table object in the + IMetastoreClient + + """ + + http_options = _BaseHiveMetastoreServiceRestTransport._BaseGetHiveTable._get_http_options() + + request, metadata = self._interceptor.pre_get_hive_table(request, metadata) + transcoded_request = _BaseHiveMetastoreServiceRestTransport._BaseGetHiveTable._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseHiveMetastoreServiceRestTransport._BaseGetHiveTable._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.biglake.hive_v1.HiveMetastoreServiceClient.GetHiveTable", + extra={ + "serviceName": "google.cloud.biglake.hive.v1.HiveMetastoreService", + "rpcName": "GetHiveTable", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = HiveMetastoreServiceRestTransport._GetHiveTable._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = hive_metastore.HiveTable() + pb_resp = hive_metastore.HiveTable.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_hive_table(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_hive_table_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = hive_metastore.HiveTable.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.biglake.hive_v1.HiveMetastoreServiceClient.get_hive_table", + extra={ + "serviceName": "google.cloud.biglake.hive.v1.HiveMetastoreService", + "rpcName": "GetHiveTable", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListHiveCatalogs( + _BaseHiveMetastoreServiceRestTransport._BaseListHiveCatalogs, + HiveMetastoreServiceRestStub, + ): + def __hash__(self): + return hash("HiveMetastoreServiceRestTransport.ListHiveCatalogs") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: hive_metastore.ListHiveCatalogsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> hive_metastore.ListHiveCatalogsResponse: + r"""Call the list hive catalogs method over HTTP. + + Args: + request (~.hive_metastore.ListHiveCatalogsRequest): + The request object. Request message for the + ListHiveCatalogs method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.hive_metastore.ListHiveCatalogsResponse: + Response message for the + ListHiveCatalogs method. + + """ + + http_options = _BaseHiveMetastoreServiceRestTransport._BaseListHiveCatalogs._get_http_options() + + request, metadata = self._interceptor.pre_list_hive_catalogs( + request, metadata + ) + transcoded_request = _BaseHiveMetastoreServiceRestTransport._BaseListHiveCatalogs._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseHiveMetastoreServiceRestTransport._BaseListHiveCatalogs._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.biglake.hive_v1.HiveMetastoreServiceClient.ListHiveCatalogs", + extra={ + "serviceName": "google.cloud.biglake.hive.v1.HiveMetastoreService", + "rpcName": "ListHiveCatalogs", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + HiveMetastoreServiceRestTransport._ListHiveCatalogs._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = hive_metastore.ListHiveCatalogsResponse() + pb_resp = hive_metastore.ListHiveCatalogsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_hive_catalogs(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_hive_catalogs_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = hive_metastore.ListHiveCatalogsResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.biglake.hive_v1.HiveMetastoreServiceClient.list_hive_catalogs", + extra={ + "serviceName": "google.cloud.biglake.hive.v1.HiveMetastoreService", + "rpcName": "ListHiveCatalogs", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListHiveDatabases( + _BaseHiveMetastoreServiceRestTransport._BaseListHiveDatabases, + HiveMetastoreServiceRestStub, + ): + def __hash__(self): + return hash("HiveMetastoreServiceRestTransport.ListHiveDatabases") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: hive_metastore.ListHiveDatabasesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> hive_metastore.ListHiveDatabasesResponse: + r"""Call the list hive databases method over HTTP. + + Args: + request (~.hive_metastore.ListHiveDatabasesRequest): + The request object. Request message for the + ListHiveDatabases method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.hive_metastore.ListHiveDatabasesResponse: + Response message for the + ListHiveDatabases method. + + """ + + http_options = _BaseHiveMetastoreServiceRestTransport._BaseListHiveDatabases._get_http_options() + + request, metadata = self._interceptor.pre_list_hive_databases( + request, metadata + ) + transcoded_request = _BaseHiveMetastoreServiceRestTransport._BaseListHiveDatabases._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseHiveMetastoreServiceRestTransport._BaseListHiveDatabases._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.biglake.hive_v1.HiveMetastoreServiceClient.ListHiveDatabases", + extra={ + "serviceName": "google.cloud.biglake.hive.v1.HiveMetastoreService", + "rpcName": "ListHiveDatabases", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + HiveMetastoreServiceRestTransport._ListHiveDatabases._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = hive_metastore.ListHiveDatabasesResponse() + pb_resp = hive_metastore.ListHiveDatabasesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_hive_databases(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_hive_databases_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = hive_metastore.ListHiveDatabasesResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.biglake.hive_v1.HiveMetastoreServiceClient.list_hive_databases", + extra={ + "serviceName": "google.cloud.biglake.hive.v1.HiveMetastoreService", + "rpcName": "ListHiveDatabases", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListHiveTables( + _BaseHiveMetastoreServiceRestTransport._BaseListHiveTables, + HiveMetastoreServiceRestStub, + ): + def __hash__(self): + return hash("HiveMetastoreServiceRestTransport.ListHiveTables") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: hive_metastore.ListHiveTablesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> hive_metastore.ListHiveTablesResponse: + r"""Call the list hive tables method over HTTP. + + Args: + request (~.hive_metastore.ListHiveTablesRequest): + The request object. Request message for the + ListHiveTables method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.hive_metastore.ListHiveTablesResponse: + Response message for the + ListHiveTables method. + + """ + + http_options = _BaseHiveMetastoreServiceRestTransport._BaseListHiveTables._get_http_options() + + request, metadata = self._interceptor.pre_list_hive_tables( + request, metadata + ) + transcoded_request = _BaseHiveMetastoreServiceRestTransport._BaseListHiveTables._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseHiveMetastoreServiceRestTransport._BaseListHiveTables._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.biglake.hive_v1.HiveMetastoreServiceClient.ListHiveTables", + extra={ + "serviceName": "google.cloud.biglake.hive.v1.HiveMetastoreService", + "rpcName": "ListHiveTables", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = HiveMetastoreServiceRestTransport._ListHiveTables._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = hive_metastore.ListHiveTablesResponse() + pb_resp = hive_metastore.ListHiveTablesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_hive_tables(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_hive_tables_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = hive_metastore.ListHiveTablesResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.biglake.hive_v1.HiveMetastoreServiceClient.list_hive_tables", + extra={ + "serviceName": "google.cloud.biglake.hive.v1.HiveMetastoreService", + "rpcName": "ListHiveTables", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListPartitions( + _BaseHiveMetastoreServiceRestTransport._BaseListPartitions, + HiveMetastoreServiceRestStub, + ): + def __hash__(self): + return hash("HiveMetastoreServiceRestTransport.ListPartitions") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + stream=True, + ) + return response + + def __call__( + self, + request: hive_metastore.ListPartitionsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> rest_streaming.ResponseIterator: + r"""Call the list partitions method over HTTP. + + Args: + request (~.hive_metastore.ListPartitionsRequest): + The request object. Request message for ListPartitions. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.hive_metastore.ListPartitionsResponse: + Response message for ListPartitions. + """ + + http_options = _BaseHiveMetastoreServiceRestTransport._BaseListPartitions._get_http_options() + + request, metadata = self._interceptor.pre_list_partitions(request, metadata) + transcoded_request = _BaseHiveMetastoreServiceRestTransport._BaseListPartitions._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseHiveMetastoreServiceRestTransport._BaseListPartitions._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.biglake.hive_v1.HiveMetastoreServiceClient.ListPartitions", + extra={ + "serviceName": "google.cloud.biglake.hive.v1.HiveMetastoreService", + "rpcName": "ListPartitions", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = HiveMetastoreServiceRestTransport._ListPartitions._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = rest_streaming.ResponseIterator( + response, hive_metastore.ListPartitionsResponse + ) + + resp = self._interceptor.post_list_partitions(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_partitions_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + http_response = { + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.biglake.hive_v1.HiveMetastoreServiceClient.list_partitions", + extra={ + "serviceName": "google.cloud.biglake.hive.v1.HiveMetastoreService", + "rpcName": "ListPartitions", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateHiveCatalog( + _BaseHiveMetastoreServiceRestTransport._BaseUpdateHiveCatalog, + HiveMetastoreServiceRestStub, + ): + def __hash__(self): + return hash("HiveMetastoreServiceRestTransport.UpdateHiveCatalog") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: hive_metastore.UpdateHiveCatalogRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> hive_metastore.HiveCatalog: + r"""Call the update hive catalog method over HTTP. + + Args: + request (~.hive_metastore.UpdateHiveCatalogRequest): + The request object. Request message for the + UpdateHiveCatalog method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.hive_metastore.HiveCatalog: + The HiveCatalog contains spark/hive + databases and tables in the BigLake + Metastore. While creating resources + under a catalog, ideally ensure that the + storage bucket location, spark / hive + engine location or any other compute + location match. Catalog can be viewed + as the destination for migrating an + on-prem Hive metastore to GCP. + + """ + + http_options = _BaseHiveMetastoreServiceRestTransport._BaseUpdateHiveCatalog._get_http_options() + + request, metadata = self._interceptor.pre_update_hive_catalog( + request, metadata + ) + transcoded_request = _BaseHiveMetastoreServiceRestTransport._BaseUpdateHiveCatalog._get_transcoded_request( + http_options, request + ) + + body = _BaseHiveMetastoreServiceRestTransport._BaseUpdateHiveCatalog._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseHiveMetastoreServiceRestTransport._BaseUpdateHiveCatalog._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.biglake.hive_v1.HiveMetastoreServiceClient.UpdateHiveCatalog", + extra={ + "serviceName": "google.cloud.biglake.hive.v1.HiveMetastoreService", + "rpcName": "UpdateHiveCatalog", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + HiveMetastoreServiceRestTransport._UpdateHiveCatalog._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = hive_metastore.HiveCatalog() + pb_resp = hive_metastore.HiveCatalog.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_hive_catalog(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_hive_catalog_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = hive_metastore.HiveCatalog.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.biglake.hive_v1.HiveMetastoreServiceClient.update_hive_catalog", + extra={ + "serviceName": "google.cloud.biglake.hive.v1.HiveMetastoreService", + "rpcName": "UpdateHiveCatalog", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateHiveDatabase( + _BaseHiveMetastoreServiceRestTransport._BaseUpdateHiveDatabase, + HiveMetastoreServiceRestStub, + ): + def __hash__(self): + return hash("HiveMetastoreServiceRestTransport.UpdateHiveDatabase") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: hive_metastore.UpdateHiveDatabaseRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> hive_metastore.HiveDatabase: + r"""Call the update hive database method over HTTP. + + Args: + request (~.hive_metastore.UpdateHiveDatabaseRequest): + The request object. Request message for the + UpdateHiveDatabase method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.hive_metastore.HiveDatabase: + Stores the hive database information. + It includes the database name, + description, location and properties + associated with the database. + + """ + + http_options = _BaseHiveMetastoreServiceRestTransport._BaseUpdateHiveDatabase._get_http_options() + + request, metadata = self._interceptor.pre_update_hive_database( + request, metadata + ) + transcoded_request = _BaseHiveMetastoreServiceRestTransport._BaseUpdateHiveDatabase._get_transcoded_request( + http_options, request + ) + + body = _BaseHiveMetastoreServiceRestTransport._BaseUpdateHiveDatabase._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseHiveMetastoreServiceRestTransport._BaseUpdateHiveDatabase._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.biglake.hive_v1.HiveMetastoreServiceClient.UpdateHiveDatabase", + extra={ + "serviceName": "google.cloud.biglake.hive.v1.HiveMetastoreService", + "rpcName": "UpdateHiveDatabase", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + HiveMetastoreServiceRestTransport._UpdateHiveDatabase._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = hive_metastore.HiveDatabase() + pb_resp = hive_metastore.HiveDatabase.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_hive_database(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_hive_database_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = hive_metastore.HiveDatabase.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.biglake.hive_v1.HiveMetastoreServiceClient.update_hive_database", + extra={ + "serviceName": "google.cloud.biglake.hive.v1.HiveMetastoreService", + "rpcName": "UpdateHiveDatabase", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateHiveTable( + _BaseHiveMetastoreServiceRestTransport._BaseUpdateHiveTable, + HiveMetastoreServiceRestStub, + ): + def __hash__(self): + return hash("HiveMetastoreServiceRestTransport.UpdateHiveTable") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: hive_metastore.UpdateHiveTableRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> hive_metastore.HiveTable: + r"""Call the update hive table method over HTTP. + + Args: + request (~.hive_metastore.UpdateHiveTableRequest): + The request object. Request message for the + UpdateHiveTable method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.hive_metastore.HiveTable: + Stores the hive table information. It + includes the table name, schema (column + names and types), data location, storage + format, serde info, etc. This message + closely matches the Table object in the + IMetastoreClient + + """ + + http_options = _BaseHiveMetastoreServiceRestTransport._BaseUpdateHiveTable._get_http_options() + + request, metadata = self._interceptor.pre_update_hive_table( + request, metadata + ) + transcoded_request = _BaseHiveMetastoreServiceRestTransport._BaseUpdateHiveTable._get_transcoded_request( + http_options, request + ) + + body = _BaseHiveMetastoreServiceRestTransport._BaseUpdateHiveTable._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseHiveMetastoreServiceRestTransport._BaseUpdateHiveTable._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.biglake.hive_v1.HiveMetastoreServiceClient.UpdateHiveTable", + extra={ + "serviceName": "google.cloud.biglake.hive.v1.HiveMetastoreService", + "rpcName": "UpdateHiveTable", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = HiveMetastoreServiceRestTransport._UpdateHiveTable._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = hive_metastore.HiveTable() + pb_resp = hive_metastore.HiveTable.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_hive_table(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_hive_table_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = hive_metastore.HiveTable.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.biglake.hive_v1.HiveMetastoreServiceClient.update_hive_table", + extra={ + "serviceName": "google.cloud.biglake.hive.v1.HiveMetastoreService", + "rpcName": "UpdateHiveTable", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def batch_create_partitions( + self, + ) -> Callable[ + [hive_metastore.BatchCreatePartitionsRequest], + hive_metastore.BatchCreatePartitionsResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._BatchCreatePartitions(self._session, self._host, self._interceptor) # type: ignore + + @property + def batch_delete_partitions( + self, + ) -> Callable[[hive_metastore.BatchDeletePartitionsRequest], empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._BatchDeletePartitions(self._session, self._host, self._interceptor) # type: ignore + + @property + def batch_update_partitions( + self, + ) -> Callable[ + [hive_metastore.BatchUpdatePartitionsRequest], + hive_metastore.BatchUpdatePartitionsResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._BatchUpdatePartitions(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_hive_catalog( + self, + ) -> Callable[ + [hive_metastore.CreateHiveCatalogRequest], hive_metastore.HiveCatalog + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateHiveCatalog(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_hive_database( + self, + ) -> Callable[ + [hive_metastore.CreateHiveDatabaseRequest], hive_metastore.HiveDatabase + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateHiveDatabase(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_hive_table( + self, + ) -> Callable[[hive_metastore.CreateHiveTableRequest], hive_metastore.HiveTable]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateHiveTable(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_hive_catalog( + self, + ) -> Callable[[hive_metastore.DeleteHiveCatalogRequest], empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteHiveCatalog(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_hive_database( + self, + ) -> Callable[[hive_metastore.DeleteHiveDatabaseRequest], empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteHiveDatabase(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_hive_table( + self, + ) -> Callable[[hive_metastore.DeleteHiveTableRequest], empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteHiveTable(self._session, self._host, self._interceptor) # type: ignore + + @property + def failover_hive_catalog( + self, + ) -> Callable[ + [hive_metastore.FailoverHiveCatalogRequest], + hive_metastore.FailoverHiveCatalogResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._FailoverHiveCatalog(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_hive_catalog( + self, + ) -> Callable[[hive_metastore.GetHiveCatalogRequest], hive_metastore.HiveCatalog]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetHiveCatalog(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_hive_database( + self, + ) -> Callable[[hive_metastore.GetHiveDatabaseRequest], hive_metastore.HiveDatabase]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetHiveDatabase(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_hive_table( + self, + ) -> Callable[[hive_metastore.GetHiveTableRequest], hive_metastore.HiveTable]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetHiveTable(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_hive_catalogs( + self, + ) -> Callable[ + [hive_metastore.ListHiveCatalogsRequest], + hive_metastore.ListHiveCatalogsResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListHiveCatalogs(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_hive_databases( + self, + ) -> Callable[ + [hive_metastore.ListHiveDatabasesRequest], + hive_metastore.ListHiveDatabasesResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListHiveDatabases(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_hive_tables( + self, + ) -> Callable[ + [hive_metastore.ListHiveTablesRequest], hive_metastore.ListHiveTablesResponse + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListHiveTables(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_partitions( + self, + ) -> Callable[ + [hive_metastore.ListPartitionsRequest], hive_metastore.ListPartitionsResponse + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListPartitions(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_hive_catalog( + self, + ) -> Callable[ + [hive_metastore.UpdateHiveCatalogRequest], hive_metastore.HiveCatalog + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateHiveCatalog(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_hive_database( + self, + ) -> Callable[ + [hive_metastore.UpdateHiveDatabaseRequest], hive_metastore.HiveDatabase + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateHiveDatabase(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_hive_table( + self, + ) -> Callable[[hive_metastore.UpdateHiveTableRequest], hive_metastore.HiveTable]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateHiveTable(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("HiveMetastoreServiceRestTransport",) diff --git a/packages/google-cloud-biglake-hive/google/cloud/biglake_hive_v1/services/hive_metastore_service/transports/rest_base.py b/packages/google-cloud-biglake-hive/google/cloud/biglake_hive_v1/services/hive_metastore_service/transports/rest_base.py new file mode 100644 index 000000000000..ada9e66f403b --- /dev/null +++ b/packages/google-cloud-biglake-hive/google/cloud/biglake_hive_v1/services/hive_metastore_service/transports/rest_base.py @@ -0,0 +1,1139 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +from google.api_core import gapic_v1, path_template +from google.protobuf import json_format + +from google.cloud.biglake_hive_v1.types import hive_metastore + +from .base import DEFAULT_CLIENT_INFO, HiveMetastoreServiceTransport + + +class _BaseHiveMetastoreServiceRestTransport(HiveMetastoreServiceTransport): + """Base REST backend transport for HiveMetastoreService. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "biglake.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'biglake.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + class _BaseBatchCreatePartitions: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/hive/v1/{parent=projects/*/catalogs/*/databases/*/tables/*}/partitions:batchCreate", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = hive_metastore.BatchCreatePartitionsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseHiveMetastoreServiceRestTransport._BaseBatchCreatePartitions._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseBatchDeletePartitions: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/hive/v1/{parent=projects/*/catalogs/*/databases/*/tables/*}/partitions:batchDelete", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = hive_metastore.BatchDeletePartitionsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseHiveMetastoreServiceRestTransport._BaseBatchDeletePartitions._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseBatchUpdatePartitions: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/hive/v1/{parent=projects/*/catalogs/*/databases/*/tables/*}/partitions:batchUpdate", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = hive_metastore.BatchUpdatePartitionsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseHiveMetastoreServiceRestTransport._BaseBatchUpdatePartitions._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateHiveCatalog: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "hiveCatalogId": "", + "primaryLocation": "", + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/hive/v1/{parent=projects/*}/catalogs", + "body": "hive_catalog", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = hive_metastore.CreateHiveCatalogRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseHiveMetastoreServiceRestTransport._BaseCreateHiveCatalog._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateHiveDatabase: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "hiveDatabaseId": "", + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/hive/v1/{parent=projects/*/catalogs/*}/databases", + "body": "hive_database", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = hive_metastore.CreateHiveDatabaseRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseHiveMetastoreServiceRestTransport._BaseCreateHiveDatabase._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateHiveTable: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "hiveTableId": "", + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/hive/v1/{parent=projects/*/catalogs/*/databases/*}/tables", + "body": "hive_table", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = hive_metastore.CreateHiveTableRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseHiveMetastoreServiceRestTransport._BaseCreateHiveTable._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteHiveCatalog: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/hive/v1/{name=projects/*/catalogs/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = hive_metastore.DeleteHiveCatalogRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseHiveMetastoreServiceRestTransport._BaseDeleteHiveCatalog._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteHiveDatabase: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/hive/v1/{name=projects/*/catalogs/*/databases/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = hive_metastore.DeleteHiveDatabaseRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseHiveMetastoreServiceRestTransport._BaseDeleteHiveDatabase._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteHiveTable: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/hive/v1/{name=projects/*/catalogs/*/databases/*/tables/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = hive_metastore.DeleteHiveTableRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseHiveMetastoreServiceRestTransport._BaseDeleteHiveTable._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseFailoverHiveCatalog: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/hive/v1/{name=projects/*/catalogs/*}:failover", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = hive_metastore.FailoverHiveCatalogRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseHiveMetastoreServiceRestTransport._BaseFailoverHiveCatalog._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetHiveCatalog: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/hive/v1/{name=projects/*/catalogs/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = hive_metastore.GetHiveCatalogRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseHiveMetastoreServiceRestTransport._BaseGetHiveCatalog._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetHiveDatabase: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/hive/v1/{name=projects/*/catalogs/*/databases/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = hive_metastore.GetHiveDatabaseRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseHiveMetastoreServiceRestTransport._BaseGetHiveDatabase._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetHiveTable: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/hive/v1/{name=projects/*/catalogs/*/databases/*/tables/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = hive_metastore.GetHiveTableRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseHiveMetastoreServiceRestTransport._BaseGetHiveTable._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListHiveCatalogs: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/hive/v1/{parent=projects/*}/catalogs", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = hive_metastore.ListHiveCatalogsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseHiveMetastoreServiceRestTransport._BaseListHiveCatalogs._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListHiveDatabases: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/hive/v1/{parent=projects/*/catalogs/*}/databases", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = hive_metastore.ListHiveDatabasesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseHiveMetastoreServiceRestTransport._BaseListHiveDatabases._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListHiveTables: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/hive/v1/{parent=projects/*/catalogs/*/databases/*}/tables", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = hive_metastore.ListHiveTablesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseHiveMetastoreServiceRestTransport._BaseListHiveTables._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListPartitions: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/hive/v1/{parent=projects/*/catalogs/*/databases/*/tables/*}/partitions:list", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = hive_metastore.ListPartitionsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseHiveMetastoreServiceRestTransport._BaseListPartitions._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateHiveCatalog: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/hive/v1/{hive_catalog.name=projects/*/catalogs/*}", + "body": "hive_catalog", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = hive_metastore.UpdateHiveCatalogRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseHiveMetastoreServiceRestTransport._BaseUpdateHiveCatalog._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateHiveDatabase: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/hive/v1/{hive_database.name=projects/*/catalogs/*/databases/*}", + "body": "hive_database", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = hive_metastore.UpdateHiveDatabaseRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseHiveMetastoreServiceRestTransport._BaseUpdateHiveDatabase._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateHiveTable: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/hive/v1/{hive_table.name=projects/*/catalogs/*/databases/*/tables/*}", + "body": "hive_table", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = hive_metastore.UpdateHiveTableRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseHiveMetastoreServiceRestTransport._BaseUpdateHiveTable._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + +__all__ = ("_BaseHiveMetastoreServiceRestTransport",) diff --git a/packages/google-cloud-biglake-hive/google/cloud/biglake_hive_v1/types/__init__.py b/packages/google-cloud-biglake-hive/google/cloud/biglake_hive_v1/types/__init__.py new file mode 100644 index 000000000000..5dc3b191c16c --- /dev/null +++ b/packages/google-cloud-biglake-hive/google/cloud/biglake_hive_v1/types/__init__.py @@ -0,0 +1,94 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 .hive_metastore import ( + BatchCreatePartitionsRequest, + BatchCreatePartitionsResponse, + BatchDeletePartitionsRequest, + BatchUpdatePartitionsRequest, + BatchUpdatePartitionsResponse, + CreateHiveCatalogRequest, + CreateHiveDatabaseRequest, + CreateHiveTableRequest, + CreatePartitionRequest, + DeleteHiveCatalogRequest, + DeleteHiveDatabaseRequest, + DeleteHiveTableRequest, + FailoverHiveCatalogRequest, + FailoverHiveCatalogResponse, + FieldSchema, + GetHiveCatalogRequest, + GetHiveDatabaseRequest, + GetHiveTableRequest, + HiveCatalog, + HiveDatabase, + HiveTable, + ListHiveCatalogsRequest, + ListHiveCatalogsResponse, + ListHiveDatabasesRequest, + ListHiveDatabasesResponse, + ListHiveTablesRequest, + ListHiveTablesResponse, + ListPartitionsRequest, + ListPartitionsResponse, + Partition, + PartitionValues, + SerdeInfo, + StorageDescriptor, + UpdateHiveCatalogRequest, + UpdateHiveDatabaseRequest, + UpdateHiveTableRequest, + UpdatePartitionRequest, +) + +__all__ = ( + "BatchCreatePartitionsRequest", + "BatchCreatePartitionsResponse", + "BatchDeletePartitionsRequest", + "BatchUpdatePartitionsRequest", + "BatchUpdatePartitionsResponse", + "CreateHiveCatalogRequest", + "CreateHiveDatabaseRequest", + "CreateHiveTableRequest", + "CreatePartitionRequest", + "DeleteHiveCatalogRequest", + "DeleteHiveDatabaseRequest", + "DeleteHiveTableRequest", + "FailoverHiveCatalogRequest", + "FailoverHiveCatalogResponse", + "FieldSchema", + "GetHiveCatalogRequest", + "GetHiveDatabaseRequest", + "GetHiveTableRequest", + "HiveCatalog", + "HiveDatabase", + "HiveTable", + "ListHiveCatalogsRequest", + "ListHiveCatalogsResponse", + "ListHiveDatabasesRequest", + "ListHiveDatabasesResponse", + "ListHiveTablesRequest", + "ListHiveTablesResponse", + "ListPartitionsRequest", + "ListPartitionsResponse", + "Partition", + "PartitionValues", + "SerdeInfo", + "StorageDescriptor", + "UpdateHiveCatalogRequest", + "UpdateHiveDatabaseRequest", + "UpdateHiveTableRequest", + "UpdatePartitionRequest", +) diff --git a/packages/google-cloud-biglake-hive/google/cloud/biglake_hive_v1/types/hive_metastore.py b/packages/google-cloud-biglake-hive/google/cloud/biglake_hive_v1/types/hive_metastore.py new file mode 100644 index 000000000000..d62109387b89 --- /dev/null +++ b/packages/google-cloud-biglake-hive/google/cloud/biglake_hive_v1/types/hive_metastore.py @@ -0,0 +1,1415 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 + +from typing import MutableMapping, MutableSequence + +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.biglake.hive.v1", + manifest={ + "HiveCatalog", + "CreateHiveCatalogRequest", + "GetHiveCatalogRequest", + "ListHiveCatalogsRequest", + "ListHiveCatalogsResponse", + "UpdateHiveCatalogRequest", + "DeleteHiveCatalogRequest", + "HiveDatabase", + "CreateHiveDatabaseRequest", + "GetHiveDatabaseRequest", + "ListHiveDatabasesRequest", + "ListHiveDatabasesResponse", + "UpdateHiveDatabaseRequest", + "DeleteHiveDatabaseRequest", + "HiveTable", + "FieldSchema", + "StorageDescriptor", + "SerdeInfo", + "CreateHiveTableRequest", + "GetHiveTableRequest", + "ListHiveTablesRequest", + "ListHiveTablesResponse", + "UpdateHiveTableRequest", + "DeleteHiveTableRequest", + "Partition", + "PartitionValues", + "CreatePartitionRequest", + "BatchCreatePartitionsRequest", + "BatchCreatePartitionsResponse", + "BatchDeletePartitionsRequest", + "UpdatePartitionRequest", + "BatchUpdatePartitionsRequest", + "BatchUpdatePartitionsResponse", + "ListPartitionsRequest", + "ListPartitionsResponse", + "FailoverHiveCatalogRequest", + "FailoverHiveCatalogResponse", + }, +) + + +class HiveCatalog(proto.Message): + r"""The HiveCatalog contains spark/hive databases and tables in + the BigLake Metastore. While creating resources under a catalog, + ideally ensure that the storage bucket location, spark / hive + engine location or any other compute location match. Catalog + can be viewed as the destination for migrating an on-prem Hive + metastore to GCP. + + Attributes: + name (str): + Identifier. The resource name. Format: + projects/{project_id_or_number}/catalogs/{catalog_id} + description (str): + Optional. Stores the catalog description. + The maximum length is 4000 characters. + location_uri (str): + Required. The Cloud Storage location path + where the catalog exists. Format: + gs://bucket/path/to/catalog The maximum length + is 4000 characters. + replicas (MutableSequence[google.cloud.biglake_hive_v1.types.HiveCatalog.Replica]): + Output only. The replicas for the catalog + metadata. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The creation time of the + catalog. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The update time of the catalog. + """ + + class Replica(proto.Message): + r"""The replica of the Catalog. + + Attributes: + region (str): + Output only. The region of the replica. For example + ``us-east1``. + state (google.cloud.biglake_hive_v1.types.HiveCatalog.Replica.State): + Output only. The current state of the + replica. + """ + + class State(proto.Enum): + r"""If the catalog is replicated to multiple regions, this enum + describes the current state of the replica. + + Values: + STATE_UNSPECIFIED (0): + The replica state is unknown. + STATE_PRIMARY (1): + Indicates the replica is the writable + primary. + STATE_PRIMARY_IN_PROGRESS (2): + Indicates the replica has been recently + assigned as the primary, but not all databases + are writeable yet. + STATE_SECONDARY (3): + Indicates the replica is a read-only + secondary replica. + """ + + STATE_UNSPECIFIED = 0 + STATE_PRIMARY = 1 + STATE_PRIMARY_IN_PROGRESS = 2 + STATE_SECONDARY = 3 + + region: str = proto.Field( + proto.STRING, + number=1, + ) + state: "HiveCatalog.Replica.State" = proto.Field( + proto.ENUM, + number=2, + enum="HiveCatalog.Replica.State", + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + location_uri: str = proto.Field( + proto.STRING, + number=3, + ) + replicas: MutableSequence[Replica] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=Replica, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + + +class CreateHiveCatalogRequest(proto.Message): + r"""Request message for the CreateHiveCatalog method. + + Attributes: + parent (str): + Required. The parent resource where this catalog will be + created. Format: projects/{project_id_or_number} + hive_catalog (google.cloud.biglake_hive_v1.types.HiveCatalog): + Required. The catalog to create. The ``name`` field does not + need to be provided. Gets copied over from catalog_id. + hive_catalog_id (str): + Required. The Hive Catalog ID to use for the + catalog that will become the final component of + the catalog's resource name. The maximum length + is 256 characters. + primary_location (str): + Required. The GCP region that specifies where + the catalog metadata is stored, e.g. + us-central1, EU, etc. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + hive_catalog: "HiveCatalog" = proto.Field( + proto.MESSAGE, + number=2, + message="HiveCatalog", + ) + hive_catalog_id: str = proto.Field( + proto.STRING, + number=3, + ) + primary_location: str = proto.Field( + proto.STRING, + number=4, + ) + + +class GetHiveCatalogRequest(proto.Message): + r"""Request message for the GetHiveCatalog method. + + Attributes: + name (str): + Required. The name of the catalog to retrieve. Format: + projects/{project_id_or_number}/catalogs/{catalog_id} + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListHiveCatalogsRequest(proto.Message): + r"""Request message for the ListHiveCatalogs method. + + Attributes: + parent (str): + Required. The project to list catalogs from. Format: + projects/{project_id_or_number} + page_size (int): + Optional. Page size for pagination. + page_token (str): + Optional. Page token for pagination. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListHiveCatalogsResponse(proto.Message): + r"""Response message for the ListHiveCatalogs method. + + Attributes: + catalogs (MutableSequence[google.cloud.biglake_hive_v1.types.HiveCatalog]): + Output only. The catalogs from the specified + project. + next_page_token (str): + Output only. A token, which can be sent as ``page_token`` to + retrieve the next page. If this field is omitted, there are + no subsequent pages. + unreachable (MutableSequence[str]): + Output only. The list of unreachable cloud + regions. If non-empty, the result set might be + incomplete. + """ + + @property + def raw_page(self): + return self + + catalogs: MutableSequence["HiveCatalog"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="HiveCatalog", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class UpdateHiveCatalogRequest(proto.Message): + r"""Request message for the UpdateHiveCatalog method. + + Attributes: + hive_catalog (google.cloud.biglake_hive_v1.types.HiveCatalog): + Required. The hive catalog to update. The name under the + catalog is used to identify the catalog. Format: + projects/{project_id_or_number}/catalogs/{catalog_id} + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The list of fields to update. + + For the ``FieldMask`` definition, see + https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask + If not set, defaults to all of the fields that are allowed + to update. + """ + + hive_catalog: "HiveCatalog" = proto.Field( + proto.MESSAGE, + number=1, + message="HiveCatalog", + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteHiveCatalogRequest(proto.Message): + r"""Request message for the DeleteHiveCatalog method. + + Attributes: + name (str): + Required. The name of the catalog to delete. Format: + projects/{project_id_or_number}/catalogs/{catalog_id} + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class HiveDatabase(proto.Message): + r"""Stores the hive database information. It includes the + database name, description, location and properties associated + with the database. + + Attributes: + name (str): + Identifier. The resource name. Format: + projects/{project_id_or_number}/catalogs/{catalog_id}/databases/{database_id} + description (str): + Optional. Stores the database description. + The maximum length is 4000 characters. + location_uri (str): + Optional. The Cloud Storage location path where the database + exists. Format: ``gs://bucket/path/to/database`` If + unspecified, the database will be stored in the catalog + location. The maximum length is 4000 characters. + parameters (MutableMapping[str, str]): + Optional. Stores the properties associated + with the database. The maximum size is 2 MiB. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The creation time of the + database. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The update time of the database. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + location_uri: str = proto.Field( + proto.STRING, + number=3, + ) + parameters: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=4, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + + +class CreateHiveDatabaseRequest(proto.Message): + r"""Request message for the CreateHiveDatabase method. + + Attributes: + parent (str): + Required. The parent resource where this database will be + created. Format: + projects/{project_id_or_number}/catalogs/{catalog_id} + hive_database (google.cloud.biglake_hive_v1.types.HiveDatabase): + Required. The database to create. The ``name`` field does + not need to be provided. + hive_database_id (str): + Required. The ID to use for the Hive + Database. The maximum length is 128 characters. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + hive_database: "HiveDatabase" = proto.Field( + proto.MESSAGE, + number=2, + message="HiveDatabase", + ) + hive_database_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class GetHiveDatabaseRequest(proto.Message): + r"""Request message for the GetHiveDatabase method. + + Attributes: + name (str): + Required. The name of the database to retrieve. Format: + projects/{project_id_or_number}/catalogs/{catalog_id}/databases/{database_id} + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListHiveDatabasesRequest(proto.Message): + r"""Request message for the ListHiveDatabases method. + + Attributes: + parent (str): + Required. The hive catalog to list databases from. Format: + projects/{project_id_or_number}/catalogs/{catalog_id} + page_size (int): + Optional. Page size for pagination. + page_token (str): + Optional. PageToken for pagination. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListHiveDatabasesResponse(proto.Message): + r"""Response message for the ListHiveDatabases method. + + Attributes: + databases (MutableSequence[google.cloud.biglake_hive_v1.types.HiveDatabase]): + Output only. The databases from the specified + project and catalog. + next_page_token (str): + Output only. A token, which can be sent as ``page_token`` to + retrieve the next page. If this field is omitted, there are + no subsequent pages. + """ + + @property + def raw_page(self): + return self + + databases: MutableSequence["HiveDatabase"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="HiveDatabase", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class UpdateHiveDatabaseRequest(proto.Message): + r"""Request message for the UpdateHiveDatabase method. + + Attributes: + hive_database (google.cloud.biglake_hive_v1.types.HiveDatabase): + Required. The database to update. + + The database's ``name`` field is used to identify the + database to update. Format: + projects/{project_id_or_number}/catalogs/{catalog_id}/databases/{database_id} + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The list of fields to update. + """ + + hive_database: "HiveDatabase" = proto.Field( + proto.MESSAGE, + number=1, + message="HiveDatabase", + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteHiveDatabaseRequest(proto.Message): + r"""Request message for the DeleteHiveDatabase method. + + Attributes: + name (str): + Required. The name of the database to delete. Format: + projects/{project_id_or_number}/catalogs/{catalog_id}/databases/{database_id} + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class HiveTable(proto.Message): + r"""Stores the hive table information. It includes the table + name, schema (column names and types), data location, storage + format, serde info, etc. This message closely matches the Table + object in the IMetastoreClient + + Attributes: + name (str): + Identifier. The resource name. Format: + projects/{project_id_or_number}/catalogs/{catalog_id}/databases/{database_id}/tables/{table_id} + description (str): + Optional. Description of the table. The + maximum length is 4000 characters. + storage_descriptor (google.cloud.biglake_hive_v1.types.StorageDescriptor): + Required. Storage descriptor of the table. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The creation time of the table. + partition_keys (MutableSequence[google.cloud.biglake_hive_v1.types.FieldSchema]): + Optional. The partition keys of the table. + parameters (MutableMapping[str, str]): + Optional. Stores the properties associated + with the table. The maximum size is 4MiB. + view_original_text (str): + Optional. The original view text. Empty for + non-view. The maximum size is 16MiB. + view_expanded_text (str): + Optional. The expanded view text. Empty for + non-view. The maximum size is 16MiB. + table_type (str): + Output only. The type of the table. This is + EXTERNAL for BigLake hive tables. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The update time of the table. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + storage_descriptor: "StorageDescriptor" = proto.Field( + proto.MESSAGE, + number=3, + message="StorageDescriptor", + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + partition_keys: MutableSequence["FieldSchema"] = proto.RepeatedField( + proto.MESSAGE, + number=7, + message="FieldSchema", + ) + parameters: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=8, + ) + view_original_text: str = proto.Field( + proto.STRING, + number=9, + ) + view_expanded_text: str = proto.Field( + proto.STRING, + number=10, + ) + table_type: str = proto.Field( + proto.STRING, + number=11, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=12, + message=timestamp_pb2.Timestamp, + ) + + +class FieldSchema(proto.Message): + r"""Field schema information. + + Attributes: + name (str): + Required. Name of the field. The maximum + length is 767 characters. + type_ (str): + Required. Type of the field. The maximum + length is 128 characters. + comment (str): + Optional. Comment of the field. The maximum + length is 256 characters. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + type_: str = proto.Field( + proto.STRING, + number=2, + ) + comment: str = proto.Field( + proto.STRING, + number=3, + ) + + +class StorageDescriptor(proto.Message): + r"""Contains information about the physical storage of the table + data. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + columns (MutableSequence[google.cloud.biglake_hive_v1.types.FieldSchema]): + Required. Specifies the columns of the table. + location_uri (str): + Optional. The Cloud storage uri where the table is located. + Defaults to ``/``. The + maximum length is 4000 characters. + input_format (str): + Optional. The fully qualified Java class name + of the input format. The maximum length is 4000 + characters. + output_format (str): + Optional. The fully qualified Java class name + of the output format. The maximum length is 4000 + characters. + compressed (bool): + Optional. Whether the table is compressed. + + This field is a member of `oneof`_ ``_compressed``. + num_buckets (int): + Optional. The number of buckets in the table. + + This field is a member of `oneof`_ ``_num_buckets``. + serde_info (google.cloud.biglake_hive_v1.types.SerdeInfo): + Optional. Serialization and deserialization + information. + bucket_cols (MutableSequence[str]): + Optional. Reducer grouping columns and + clustering columns and bucketing columns + sort_cols (MutableSequence[google.cloud.biglake_hive_v1.types.StorageDescriptor.Order]): + Optional. Sort order of the data in each + bucket + parameters (MutableMapping[str, str]): + Optional. Key-value pairs for the storage + descriptor. The maximum size is 10Kib. + skewed_info (google.cloud.biglake_hive_v1.types.StorageDescriptor.SkewedInfo): + Optional. Table data skew information. + stored_as_sub_dirs (bool): + Optional. Whether the table is stored as sub + directories. + + This field is a member of `oneof`_ ``_stored_as_sub_dirs``. + """ + + class Order(proto.Message): + r"""Sort order of the stored data per column. + + Attributes: + col (str): + Required. The column name. The maximum length + is 767 characters. + order (int): + Required. Defines the sort order of the + column. Ascending if 1, descending if 0. + """ + + col: str = proto.Field( + proto.STRING, + number=1, + ) + order: int = proto.Field( + proto.INT32, + number=2, + ) + + class SkewedInfo(proto.Message): + r"""Stores all the information about skewed table. + + Attributes: + skewed_col_names (MutableSequence[str]): + Required. The column names that are skewed. + The maximum length is 256 characters per column + name. + skewed_col_values (MutableSequence[google.cloud.biglake_hive_v1.types.StorageDescriptor.SkewedInfo.SkewedColumnValue]): + Required. The skewed column values. + skewed_key_values_locations (MutableSequence[google.cloud.biglake_hive_v1.types.StorageDescriptor.SkewedInfo.SkewedKeyValuesLocation]): + Required. The skewed key values locations. + """ + + class SkewedColumnValue(proto.Message): + r"""The skewed column values. + + Attributes: + values (MutableSequence[str]): + Required. The skewed column values. The + maximum length is 256 characters per value. + """ + + values: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + + class SkewedKeyValuesLocation(proto.Message): + r"""The skewed key values and their corresponding location. + + Attributes: + values (MutableSequence[str]): + Required. The skewed column values. The + maximum length is 256 characters per value. + location (str): + Required. The location of the skewed column + values. The maximum length is 4000 characters. + """ + + values: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + location: str = proto.Field( + proto.STRING, + number=2, + ) + + skewed_col_names: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + skewed_col_values: MutableSequence[ + "StorageDescriptor.SkewedInfo.SkewedColumnValue" + ] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="StorageDescriptor.SkewedInfo.SkewedColumnValue", + ) + skewed_key_values_locations: MutableSequence[ + "StorageDescriptor.SkewedInfo.SkewedKeyValuesLocation" + ] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message="StorageDescriptor.SkewedInfo.SkewedKeyValuesLocation", + ) + + columns: MutableSequence["FieldSchema"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="FieldSchema", + ) + location_uri: str = proto.Field( + proto.STRING, + number=2, + ) + input_format: str = proto.Field( + proto.STRING, + number=3, + ) + output_format: str = proto.Field( + proto.STRING, + number=4, + ) + compressed: bool = proto.Field( + proto.BOOL, + number=5, + optional=True, + ) + num_buckets: int = proto.Field( + proto.INT32, + number=6, + optional=True, + ) + serde_info: "SerdeInfo" = proto.Field( + proto.MESSAGE, + number=7, + message="SerdeInfo", + ) + bucket_cols: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=8, + ) + sort_cols: MutableSequence[Order] = proto.RepeatedField( + proto.MESSAGE, + number=9, + message=Order, + ) + parameters: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=10, + ) + skewed_info: SkewedInfo = proto.Field( + proto.MESSAGE, + number=11, + message=SkewedInfo, + ) + stored_as_sub_dirs: bool = proto.Field( + proto.BOOL, + number=12, + optional=True, + ) + + +class SerdeInfo(proto.Message): + r"""Serialization and deserialization information. + + Attributes: + name (str): + Required. Name of the SerDe. Table name by + default. The maximum length is 128 characters. + serialization_lib (str): + Required. The fully qualified Java class name + of the serialization library. The maximum length + is 4000 characters. + description (str): + Optional. Description of the serde. The + maximum length is 4000 characters. + parameters (MutableMapping[str, str]): + Optional. Parameters of the serde. The + maximum size is 10Kib. + serializer_class (str): + Optional. The fully qualified Java class name + of the serializer. The maximum length is 4000 + characters. + deserializer_class (str): + Optional. The fully qualified Java class name + of the deserializer. The maximum length is 4000 + characters. + serde_type (google.cloud.biglake_hive_v1.types.SerdeInfo.SerdeType): + Optional. The serde type. + """ + + class SerdeType(proto.Enum): + r"""The serde types. + + Values: + SERDE_TYPE_UNSPECIFIED (0): + The serde type is not specified. + HIVE (1): + Hive. + SCHEMA_REGISTRY (2): + Schema registry. + """ + + SERDE_TYPE_UNSPECIFIED = 0 + HIVE = 1 + SCHEMA_REGISTRY = 2 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + serialization_lib: str = proto.Field( + proto.STRING, + number=2, + ) + description: str = proto.Field( + proto.STRING, + number=3, + ) + parameters: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=4, + ) + serializer_class: str = proto.Field( + proto.STRING, + number=5, + ) + deserializer_class: str = proto.Field( + proto.STRING, + number=6, + ) + serde_type: SerdeType = proto.Field( + proto.ENUM, + number=7, + enum=SerdeType, + ) + + +class CreateHiveTableRequest(proto.Message): + r"""Request message for the CreateHiveTable method. + + Attributes: + parent (str): + Required. The parent resource for the table to be created. + Format: + projects/{project_id_or_number}/catalogs/{catalog_id}/databases/{database_id} + hive_table (google.cloud.biglake_hive_v1.types.HiveTable): + Required. The Hive Table to create. The ``name`` field does + not need to be provided. + hive_table_id (str): + Required. The Hive Table ID to use for the + table that will become the final component of + the table's resource name. The maximum length is + 256 characters. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + hive_table: "HiveTable" = proto.Field( + proto.MESSAGE, + number=2, + message="HiveTable", + ) + hive_table_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class GetHiveTableRequest(proto.Message): + r"""Request message for the GetHiveTable method. + + Attributes: + name (str): + Required. The name of the table to retrieve. Format: + projects/{project_id_or_number}/catalogs/{catalog_id}/databases/{database_id}/tables/{table_id} + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListHiveTablesRequest(proto.Message): + r"""Request message for the ListHiveTables method. + + Attributes: + parent (str): + Required. The database to list tables from. Format: + projects/{project_id_or_number}/catalogs/{catalog_id}/databases/{database_id} + page_size (int): + Optional. Page size for pagination. + page_token (str): + Optional. PageToken for pagination. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListHiveTablesResponse(proto.Message): + r"""Response message for the ListHiveTables method. + + Attributes: + tables (MutableSequence[google.cloud.biglake_hive_v1.types.HiveTable]): + Output only. The tables from the specified + project, catalog and database. + next_page_token (str): + Output only. A token, which can be sent as ``page_token`` to + retrieve the next page. If this field is omitted, there are + no subsequent pages. + """ + + @property + def raw_page(self): + return self + + tables: MutableSequence["HiveTable"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="HiveTable", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class UpdateHiveTableRequest(proto.Message): + r"""Request message for the UpdateHiveTable method. + + Attributes: + hive_table (google.cloud.biglake_hive_v1.types.HiveTable): + Required. The table to update. + + The table's ``name`` field is used to identify the table to + update. Format: + projects/{project_id_or_number}/catalogs/{catalog_id}/databases/{database_id}/tables/{table_id} + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The list of fields to update. + """ + + hive_table: "HiveTable" = proto.Field( + proto.MESSAGE, + number=1, + message="HiveTable", + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteHiveTableRequest(proto.Message): + r"""Request message for the DeleteHiveTable method. + + Attributes: + name (str): + Required. The name of the database to delete. Format: + projects/{project_id_or_number}/catalogs/{catalog_id}/databases/{database_id}/tables/{table_id} + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class Partition(proto.Message): + r"""Information about a Hive partition. + + Attributes: + values (MutableSequence[str]): + Required. Represents the values of the + partition keys, where each value corresponds to + a specific partition key in the order in which + the keys are defined. Each value is limited to + 1024 characters. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The creation time of the + partition. + storage_descriptor (google.cloud.biglake_hive_v1.types.StorageDescriptor): + Optional. Contains information about the + physical storage of the data in the partition. + parameters (MutableMapping[str, str]): + Optional. Additional parameters or metadata + associated with the partition. Maximum size 10 + KiB. + fields (MutableSequence[google.cloud.biglake_hive_v1.types.FieldSchema]): + Optional. List of columns. + """ + + values: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + storage_descriptor: "StorageDescriptor" = proto.Field( + proto.MESSAGE, + number=3, + message="StorageDescriptor", + ) + parameters: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=4, + ) + fields: MutableSequence["FieldSchema"] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message="FieldSchema", + ) + + +class PartitionValues(proto.Message): + r"""Represents the values of a partition. + + Attributes: + values (MutableSequence[str]): + Required. The values of the partition keys, + where each value corresponds to a specific + partition key in the order in which the keys are + defined. + """ + + values: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + + +class CreatePartitionRequest(proto.Message): + r"""Request message for CreatePartition. The Partition is + uniquely identified by values, which is an ordered list. Hence, + there is no separate name or partition id field. + + Attributes: + parent (str): + Required. Reference to the table to where the + partition to be added, in the format of + projects/{project}/catalogs/{catalogs}/databases/{databases}/tables/{table}. + partition (google.cloud.biglake_hive_v1.types.Partition): + Required. The partition to be added. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + partition: "Partition" = proto.Field( + proto.MESSAGE, + number=2, + message="Partition", + ) + + +class BatchCreatePartitionsRequest(proto.Message): + r"""Request message for the BatchCreatePartitions method. + + Attributes: + parent (str): + Required. Reference to the table to where the + partitions to be added, in the format of + projects/{project}/catalogs/{catalogs}/databases/{database}/tables/{table}. + requests (MutableSequence[google.cloud.biglake_hive_v1.types.CreatePartitionRequest]): + Required. Requests to add partitions to the + table. + skip_existing_partitions (bool): + Optional. Corresponds to the ``ifNotExists`` flag in the + Hive Metastore APIs. If the flag is set to false, the server + will return ALREADY_EXISTS if any partition already exists. + If the flag is set to true, the server will skip existing + partitions and insert only the non-existing partitions. A + maximum of 900 partitions can be inserted in a batch. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + requests: MutableSequence["CreatePartitionRequest"] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="CreatePartitionRequest", + ) + skip_existing_partitions: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +class BatchCreatePartitionsResponse(proto.Message): + r"""Response message for BatchCreatePartitions. + + Attributes: + partitions (MutableSequence[google.cloud.biglake_hive_v1.types.Partition]): + The list of partitions that have been added. + """ + + partitions: MutableSequence["Partition"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Partition", + ) + + +class BatchDeletePartitionsRequest(proto.Message): + r"""Request message for BatchDeletePartitions. The Partition is + uniquely identified by values, which is an ordered list. Hence, + there is no separate name or partition id field. + + Attributes: + parent (str): + Required. Reference to the table to which + these partitions belong, in the format of + projects/{project}/catalogs/{catalogs}/databases/{database}/tables/{table}. + partition_values (MutableSequence[google.cloud.biglake_hive_v1.types.PartitionValues]): + Required. The list of partitions (identified + by its values) to be deleted. A maximum of 900 + partitions can be deleted in a batch. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + partition_values: MutableSequence["PartitionValues"] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="PartitionValues", + ) + + +class UpdatePartitionRequest(proto.Message): + r"""Request message for UpdatePartition. + + Attributes: + partition (google.cloud.biglake_hive_v1.types.Partition): + Required. The partition to be updated. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The list of fields to update. + """ + + partition: "Partition" = proto.Field( + proto.MESSAGE, + number=1, + message="Partition", + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class BatchUpdatePartitionsRequest(proto.Message): + r"""Request message for BatchUpdatePartitions. + + Attributes: + parent (str): + Required. Reference to the table to which + these partitions belong, in the format of + projects/{project}/catalogs/{catalogs}/databases/{database}/tables/{table}. + requests (MutableSequence[google.cloud.biglake_hive_v1.types.UpdatePartitionRequest]): + Required. Requests to update partitions in + the table. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + requests: MutableSequence["UpdatePartitionRequest"] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="UpdatePartitionRequest", + ) + + +class BatchUpdatePartitionsResponse(proto.Message): + r"""Response message for BatchUpdatePartitions. + + Attributes: + partitions (MutableSequence[google.cloud.biglake_hive_v1.types.Partition]): + The list of partitions that have been + updated. A maximum of 900 partitions can be + updated in a batch. + """ + + partitions: MutableSequence["Partition"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Partition", + ) + + +class ListPartitionsRequest(proto.Message): + r"""Request message for ListPartitions. + + Attributes: + parent (str): + Required. Reference to the table to which + these partitions belong, in the format of + projects/{project}/catalogs/{catalogs}/databases/{database}/tables/{table}. + filter (str): + Optional. SQL text filtering statement, similar to a + ``WHERE`` clause in a query. Only supports single-row + expressions. Aggregate functions are not supported. + + Examples: + + - ``"int_field > 5"`` + - ``"date_field = CAST('2014-9-27' as DATE)"`` + - ``"nullable_field is not NULL"`` + - ``"st_equals(geo_field, st_geofromtext("POINT(2, 2)"))"`` + - ``"numeric_field BETWEEN 1.0 AND 5.0"`` + + Restricted to a maximum length of 1 MB. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + filter: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListPartitionsResponse(proto.Message): + r"""Response message for ListPartitions. + + Attributes: + partitions (MutableSequence[google.cloud.biglake_hive_v1.types.Partition]): + Output only. List of partitions. + """ + + partitions: MutableSequence["Partition"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Partition", + ) + + +class FailoverHiveCatalogRequest(proto.Message): + r"""Request message for FailoverHiveCatalog. + + Attributes: + name (str): + Required. The name of the catalog in the form + "projects/{project_id}/catalogs/{catalog_id}". + primary_replica (str): + Required. The region being assigned as the + new primary replica region. For example + "us-east1". This must be one of the replica + regions in the catalog's list of replicas marked + as a "secondary". + validate_only (bool): + Optional. If set, only validate the request, but do not + perform the update. This can be used to inspect the + replication_time at any time, including before performing a + fail-over. + conditional_failover_replication_time (google.protobuf.timestamp_pb2.Timestamp): + Optional. If unset, wait for all data from + the source region to replicate to the new + primary region before completing the failover, + with no data loss (also called "soft failover"). + If set, failover immediately, accepting the loss + of any data committed in the source region after + this timestamp, that has not yet replicated. If + any data committed before this time has not + replicated, the failover will not be performed + and an error will be returned (also called "hard + failover"). + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + primary_replica: str = proto.Field( + proto.STRING, + number=2, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=3, + ) + conditional_failover_replication_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + + +class FailoverHiveCatalogResponse(proto.Message): + r"""Response message for FailoverHiveCatalog. + + Attributes: + replication_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The min timestamp for which all namespaces and + table metadata have been replicated in the region specified + as the new primary_replica. Some resources may have been + replicated more recently than this timestamp. If empty, the + replica has just been created and has not yet been fully + initialized. + """ + + replication_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_batch_create_partitions_async.py b/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_batch_create_partitions_async.py new file mode 100644 index 000000000000..2498a7dd3f13 --- /dev/null +++ b/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_batch_create_partitions_async.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for BatchCreatePartitions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-biglake-hive + + +# [START biglake_v1_generated_HiveMetastoreService_BatchCreatePartitions_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import biglake_hive_v1 + + +async def sample_batch_create_partitions(): + # Create a client + client = biglake_hive_v1.HiveMetastoreServiceAsyncClient() + + # Initialize request argument(s) + requests = biglake_hive_v1.CreatePartitionRequest() + requests.parent = "parent_value" + requests.partition.values = ["values_value1", "values_value2"] + + request = biglake_hive_v1.BatchCreatePartitionsRequest( + parent="parent_value", + requests=requests, + ) + + # Make the request + response = await client.batch_create_partitions(request=request) + + # Handle the response + print(response) + + +# [END biglake_v1_generated_HiveMetastoreService_BatchCreatePartitions_async] diff --git a/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_batch_create_partitions_sync.py b/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_batch_create_partitions_sync.py new file mode 100644 index 000000000000..606131a68d8b --- /dev/null +++ b/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_batch_create_partitions_sync.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for BatchCreatePartitions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-biglake-hive + + +# [START biglake_v1_generated_HiveMetastoreService_BatchCreatePartitions_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import biglake_hive_v1 + + +def sample_batch_create_partitions(): + # Create a client + client = biglake_hive_v1.HiveMetastoreServiceClient() + + # Initialize request argument(s) + requests = biglake_hive_v1.CreatePartitionRequest() + requests.parent = "parent_value" + requests.partition.values = ["values_value1", "values_value2"] + + request = biglake_hive_v1.BatchCreatePartitionsRequest( + parent="parent_value", + requests=requests, + ) + + # Make the request + response = client.batch_create_partitions(request=request) + + # Handle the response + print(response) + + +# [END biglake_v1_generated_HiveMetastoreService_BatchCreatePartitions_sync] diff --git a/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_batch_delete_partitions_async.py b/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_batch_delete_partitions_async.py new file mode 100644 index 000000000000..87a87f4ae8e5 --- /dev/null +++ b/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_batch_delete_partitions_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for BatchDeletePartitions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-biglake-hive + + +# [START biglake_v1_generated_HiveMetastoreService_BatchDeletePartitions_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import biglake_hive_v1 + + +async def sample_batch_delete_partitions(): + # Create a client + client = biglake_hive_v1.HiveMetastoreServiceAsyncClient() + + # Initialize request argument(s) + partition_values = biglake_hive_v1.PartitionValues() + partition_values.values = ["values_value1", "values_value2"] + + request = biglake_hive_v1.BatchDeletePartitionsRequest( + parent="parent_value", + partition_values=partition_values, + ) + + # Make the request + await client.batch_delete_partitions(request=request) + + +# [END biglake_v1_generated_HiveMetastoreService_BatchDeletePartitions_async] diff --git a/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_batch_delete_partitions_sync.py b/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_batch_delete_partitions_sync.py new file mode 100644 index 000000000000..450787a1d09f --- /dev/null +++ b/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_batch_delete_partitions_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for BatchDeletePartitions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-biglake-hive + + +# [START biglake_v1_generated_HiveMetastoreService_BatchDeletePartitions_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import biglake_hive_v1 + + +def sample_batch_delete_partitions(): + # Create a client + client = biglake_hive_v1.HiveMetastoreServiceClient() + + # Initialize request argument(s) + partition_values = biglake_hive_v1.PartitionValues() + partition_values.values = ["values_value1", "values_value2"] + + request = biglake_hive_v1.BatchDeletePartitionsRequest( + parent="parent_value", + partition_values=partition_values, + ) + + # Make the request + client.batch_delete_partitions(request=request) + + +# [END biglake_v1_generated_HiveMetastoreService_BatchDeletePartitions_sync] diff --git a/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_batch_update_partitions_async.py b/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_batch_update_partitions_async.py new file mode 100644 index 000000000000..6ae6fcd2b4a3 --- /dev/null +++ b/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_batch_update_partitions_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for BatchUpdatePartitions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-biglake-hive + + +# [START biglake_v1_generated_HiveMetastoreService_BatchUpdatePartitions_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import biglake_hive_v1 + + +async def sample_batch_update_partitions(): + # Create a client + client = biglake_hive_v1.HiveMetastoreServiceAsyncClient() + + # Initialize request argument(s) + requests = biglake_hive_v1.UpdatePartitionRequest() + requests.partition.values = ["values_value1", "values_value2"] + + request = biglake_hive_v1.BatchUpdatePartitionsRequest( + parent="parent_value", + requests=requests, + ) + + # Make the request + response = await client.batch_update_partitions(request=request) + + # Handle the response + print(response) + + +# [END biglake_v1_generated_HiveMetastoreService_BatchUpdatePartitions_async] diff --git a/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_batch_update_partitions_sync.py b/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_batch_update_partitions_sync.py new file mode 100644 index 000000000000..dac24f19588c --- /dev/null +++ b/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_batch_update_partitions_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for BatchUpdatePartitions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-biglake-hive + + +# [START biglake_v1_generated_HiveMetastoreService_BatchUpdatePartitions_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import biglake_hive_v1 + + +def sample_batch_update_partitions(): + # Create a client + client = biglake_hive_v1.HiveMetastoreServiceClient() + + # Initialize request argument(s) + requests = biglake_hive_v1.UpdatePartitionRequest() + requests.partition.values = ["values_value1", "values_value2"] + + request = biglake_hive_v1.BatchUpdatePartitionsRequest( + parent="parent_value", + requests=requests, + ) + + # Make the request + response = client.batch_update_partitions(request=request) + + # Handle the response + print(response) + + +# [END biglake_v1_generated_HiveMetastoreService_BatchUpdatePartitions_sync] diff --git a/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_create_hive_catalog_async.py b/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_create_hive_catalog_async.py new file mode 100644 index 000000000000..8dd59c2b57e6 --- /dev/null +++ b/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_create_hive_catalog_async.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateHiveCatalog +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-biglake-hive + + +# [START biglake_v1_generated_HiveMetastoreService_CreateHiveCatalog_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import biglake_hive_v1 + + +async def sample_create_hive_catalog(): + # Create a client + client = biglake_hive_v1.HiveMetastoreServiceAsyncClient() + + # Initialize request argument(s) + hive_catalog = biglake_hive_v1.HiveCatalog() + hive_catalog.location_uri = "location_uri_value" + + request = biglake_hive_v1.CreateHiveCatalogRequest( + parent="parent_value", + hive_catalog=hive_catalog, + hive_catalog_id="hive_catalog_id_value", + primary_location="primary_location_value", + ) + + # Make the request + response = await client.create_hive_catalog(request=request) + + # Handle the response + print(response) + + +# [END biglake_v1_generated_HiveMetastoreService_CreateHiveCatalog_async] diff --git a/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_create_hive_catalog_sync.py b/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_create_hive_catalog_sync.py new file mode 100644 index 000000000000..08645cadee10 --- /dev/null +++ b/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_create_hive_catalog_sync.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateHiveCatalog +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-biglake-hive + + +# [START biglake_v1_generated_HiveMetastoreService_CreateHiveCatalog_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import biglake_hive_v1 + + +def sample_create_hive_catalog(): + # Create a client + client = biglake_hive_v1.HiveMetastoreServiceClient() + + # Initialize request argument(s) + hive_catalog = biglake_hive_v1.HiveCatalog() + hive_catalog.location_uri = "location_uri_value" + + request = biglake_hive_v1.CreateHiveCatalogRequest( + parent="parent_value", + hive_catalog=hive_catalog, + hive_catalog_id="hive_catalog_id_value", + primary_location="primary_location_value", + ) + + # Make the request + response = client.create_hive_catalog(request=request) + + # Handle the response + print(response) + + +# [END biglake_v1_generated_HiveMetastoreService_CreateHiveCatalog_sync] diff --git a/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_create_hive_database_async.py b/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_create_hive_database_async.py new file mode 100644 index 000000000000..f557edb83a3c --- /dev/null +++ b/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_create_hive_database_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateHiveDatabase +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-biglake-hive + + +# [START biglake_v1_generated_HiveMetastoreService_CreateHiveDatabase_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import biglake_hive_v1 + + +async def sample_create_hive_database(): + # Create a client + client = biglake_hive_v1.HiveMetastoreServiceAsyncClient() + + # Initialize request argument(s) + request = biglake_hive_v1.CreateHiveDatabaseRequest( + parent="parent_value", + hive_database_id="hive_database_id_value", + ) + + # Make the request + response = await client.create_hive_database(request=request) + + # Handle the response + print(response) + + +# [END biglake_v1_generated_HiveMetastoreService_CreateHiveDatabase_async] diff --git a/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_create_hive_database_sync.py b/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_create_hive_database_sync.py new file mode 100644 index 000000000000..ba57b6c1613a --- /dev/null +++ b/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_create_hive_database_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateHiveDatabase +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-biglake-hive + + +# [START biglake_v1_generated_HiveMetastoreService_CreateHiveDatabase_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import biglake_hive_v1 + + +def sample_create_hive_database(): + # Create a client + client = biglake_hive_v1.HiveMetastoreServiceClient() + + # Initialize request argument(s) + request = biglake_hive_v1.CreateHiveDatabaseRequest( + parent="parent_value", + hive_database_id="hive_database_id_value", + ) + + # Make the request + response = client.create_hive_database(request=request) + + # Handle the response + print(response) + + +# [END biglake_v1_generated_HiveMetastoreService_CreateHiveDatabase_sync] diff --git a/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_create_hive_table_async.py b/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_create_hive_table_async.py new file mode 100644 index 000000000000..c33629feb0dc --- /dev/null +++ b/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_create_hive_table_async.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateHiveTable +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-biglake-hive + + +# [START biglake_v1_generated_HiveMetastoreService_CreateHiveTable_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import biglake_hive_v1 + + +async def sample_create_hive_table(): + # Create a client + client = biglake_hive_v1.HiveMetastoreServiceAsyncClient() + + # Initialize request argument(s) + hive_table = biglake_hive_v1.HiveTable() + hive_table.storage_descriptor.columns.name = "name_value" + hive_table.storage_descriptor.columns.type_ = "type__value" + + request = biglake_hive_v1.CreateHiveTableRequest( + parent="parent_value", + hive_table=hive_table, + hive_table_id="hive_table_id_value", + ) + + # Make the request + response = await client.create_hive_table(request=request) + + # Handle the response + print(response) + + +# [END biglake_v1_generated_HiveMetastoreService_CreateHiveTable_async] diff --git a/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_create_hive_table_sync.py b/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_create_hive_table_sync.py new file mode 100644 index 000000000000..21344ca795c5 --- /dev/null +++ b/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_create_hive_table_sync.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateHiveTable +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-biglake-hive + + +# [START biglake_v1_generated_HiveMetastoreService_CreateHiveTable_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import biglake_hive_v1 + + +def sample_create_hive_table(): + # Create a client + client = biglake_hive_v1.HiveMetastoreServiceClient() + + # Initialize request argument(s) + hive_table = biglake_hive_v1.HiveTable() + hive_table.storage_descriptor.columns.name = "name_value" + hive_table.storage_descriptor.columns.type_ = "type__value" + + request = biglake_hive_v1.CreateHiveTableRequest( + parent="parent_value", + hive_table=hive_table, + hive_table_id="hive_table_id_value", + ) + + # Make the request + response = client.create_hive_table(request=request) + + # Handle the response + print(response) + + +# [END biglake_v1_generated_HiveMetastoreService_CreateHiveTable_sync] diff --git a/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_delete_hive_catalog_async.py b/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_delete_hive_catalog_async.py new file mode 100644 index 000000000000..5b1f5e8cbb81 --- /dev/null +++ b/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_delete_hive_catalog_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteHiveCatalog +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-biglake-hive + + +# [START biglake_v1_generated_HiveMetastoreService_DeleteHiveCatalog_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import biglake_hive_v1 + + +async def sample_delete_hive_catalog(): + # Create a client + client = biglake_hive_v1.HiveMetastoreServiceAsyncClient() + + # Initialize request argument(s) + request = biglake_hive_v1.DeleteHiveCatalogRequest( + name="name_value", + ) + + # Make the request + await client.delete_hive_catalog(request=request) + + +# [END biglake_v1_generated_HiveMetastoreService_DeleteHiveCatalog_async] diff --git a/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_delete_hive_catalog_sync.py b/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_delete_hive_catalog_sync.py new file mode 100644 index 000000000000..e936b3c5e18b --- /dev/null +++ b/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_delete_hive_catalog_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteHiveCatalog +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-biglake-hive + + +# [START biglake_v1_generated_HiveMetastoreService_DeleteHiveCatalog_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import biglake_hive_v1 + + +def sample_delete_hive_catalog(): + # Create a client + client = biglake_hive_v1.HiveMetastoreServiceClient() + + # Initialize request argument(s) + request = biglake_hive_v1.DeleteHiveCatalogRequest( + name="name_value", + ) + + # Make the request + client.delete_hive_catalog(request=request) + + +# [END biglake_v1_generated_HiveMetastoreService_DeleteHiveCatalog_sync] diff --git a/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_delete_hive_database_async.py b/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_delete_hive_database_async.py new file mode 100644 index 000000000000..bd02c685fab3 --- /dev/null +++ b/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_delete_hive_database_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteHiveDatabase +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-biglake-hive + + +# [START biglake_v1_generated_HiveMetastoreService_DeleteHiveDatabase_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import biglake_hive_v1 + + +async def sample_delete_hive_database(): + # Create a client + client = biglake_hive_v1.HiveMetastoreServiceAsyncClient() + + # Initialize request argument(s) + request = biglake_hive_v1.DeleteHiveDatabaseRequest( + name="name_value", + ) + + # Make the request + await client.delete_hive_database(request=request) + + +# [END biglake_v1_generated_HiveMetastoreService_DeleteHiveDatabase_async] diff --git a/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_delete_hive_database_sync.py b/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_delete_hive_database_sync.py new file mode 100644 index 000000000000..e05111390df6 --- /dev/null +++ b/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_delete_hive_database_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteHiveDatabase +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-biglake-hive + + +# [START biglake_v1_generated_HiveMetastoreService_DeleteHiveDatabase_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import biglake_hive_v1 + + +def sample_delete_hive_database(): + # Create a client + client = biglake_hive_v1.HiveMetastoreServiceClient() + + # Initialize request argument(s) + request = biglake_hive_v1.DeleteHiveDatabaseRequest( + name="name_value", + ) + + # Make the request + client.delete_hive_database(request=request) + + +# [END biglake_v1_generated_HiveMetastoreService_DeleteHiveDatabase_sync] diff --git a/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_delete_hive_table_async.py b/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_delete_hive_table_async.py new file mode 100644 index 000000000000..9ae02ecae665 --- /dev/null +++ b/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_delete_hive_table_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteHiveTable +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-biglake-hive + + +# [START biglake_v1_generated_HiveMetastoreService_DeleteHiveTable_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import biglake_hive_v1 + + +async def sample_delete_hive_table(): + # Create a client + client = biglake_hive_v1.HiveMetastoreServiceAsyncClient() + + # Initialize request argument(s) + request = biglake_hive_v1.DeleteHiveTableRequest( + name="name_value", + ) + + # Make the request + await client.delete_hive_table(request=request) + + +# [END biglake_v1_generated_HiveMetastoreService_DeleteHiveTable_async] diff --git a/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_delete_hive_table_sync.py b/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_delete_hive_table_sync.py new file mode 100644 index 000000000000..1e61394023cc --- /dev/null +++ b/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_delete_hive_table_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteHiveTable +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-biglake-hive + + +# [START biglake_v1_generated_HiveMetastoreService_DeleteHiveTable_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import biglake_hive_v1 + + +def sample_delete_hive_table(): + # Create a client + client = biglake_hive_v1.HiveMetastoreServiceClient() + + # Initialize request argument(s) + request = biglake_hive_v1.DeleteHiveTableRequest( + name="name_value", + ) + + # Make the request + client.delete_hive_table(request=request) + + +# [END biglake_v1_generated_HiveMetastoreService_DeleteHiveTable_sync] diff --git a/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_failover_hive_catalog_async.py b/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_failover_hive_catalog_async.py new file mode 100644 index 000000000000..cf71b7c732d8 --- /dev/null +++ b/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_failover_hive_catalog_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for FailoverHiveCatalog +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-biglake-hive + + +# [START biglake_v1_generated_HiveMetastoreService_FailoverHiveCatalog_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import biglake_hive_v1 + + +async def sample_failover_hive_catalog(): + # Create a client + client = biglake_hive_v1.HiveMetastoreServiceAsyncClient() + + # Initialize request argument(s) + request = biglake_hive_v1.FailoverHiveCatalogRequest( + name="name_value", + primary_replica="primary_replica_value", + ) + + # Make the request + response = await client.failover_hive_catalog(request=request) + + # Handle the response + print(response) + + +# [END biglake_v1_generated_HiveMetastoreService_FailoverHiveCatalog_async] diff --git a/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_failover_hive_catalog_sync.py b/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_failover_hive_catalog_sync.py new file mode 100644 index 000000000000..b98c8420fd44 --- /dev/null +++ b/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_failover_hive_catalog_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for FailoverHiveCatalog +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-biglake-hive + + +# [START biglake_v1_generated_HiveMetastoreService_FailoverHiveCatalog_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import biglake_hive_v1 + + +def sample_failover_hive_catalog(): + # Create a client + client = biglake_hive_v1.HiveMetastoreServiceClient() + + # Initialize request argument(s) + request = biglake_hive_v1.FailoverHiveCatalogRequest( + name="name_value", + primary_replica="primary_replica_value", + ) + + # Make the request + response = client.failover_hive_catalog(request=request) + + # Handle the response + print(response) + + +# [END biglake_v1_generated_HiveMetastoreService_FailoverHiveCatalog_sync] diff --git a/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_get_hive_catalog_async.py b/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_get_hive_catalog_async.py new file mode 100644 index 000000000000..dd933bfa981a --- /dev/null +++ b/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_get_hive_catalog_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetHiveCatalog +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-biglake-hive + + +# [START biglake_v1_generated_HiveMetastoreService_GetHiveCatalog_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import biglake_hive_v1 + + +async def sample_get_hive_catalog(): + # Create a client + client = biglake_hive_v1.HiveMetastoreServiceAsyncClient() + + # Initialize request argument(s) + request = biglake_hive_v1.GetHiveCatalogRequest( + name="name_value", + ) + + # Make the request + response = await client.get_hive_catalog(request=request) + + # Handle the response + print(response) + + +# [END biglake_v1_generated_HiveMetastoreService_GetHiveCatalog_async] diff --git a/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_get_hive_catalog_sync.py b/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_get_hive_catalog_sync.py new file mode 100644 index 000000000000..84c877cf5e5c --- /dev/null +++ b/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_get_hive_catalog_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetHiveCatalog +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-biglake-hive + + +# [START biglake_v1_generated_HiveMetastoreService_GetHiveCatalog_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import biglake_hive_v1 + + +def sample_get_hive_catalog(): + # Create a client + client = biglake_hive_v1.HiveMetastoreServiceClient() + + # Initialize request argument(s) + request = biglake_hive_v1.GetHiveCatalogRequest( + name="name_value", + ) + + # Make the request + response = client.get_hive_catalog(request=request) + + # Handle the response + print(response) + + +# [END biglake_v1_generated_HiveMetastoreService_GetHiveCatalog_sync] diff --git a/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_get_hive_database_async.py b/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_get_hive_database_async.py new file mode 100644 index 000000000000..4b37e45a2710 --- /dev/null +++ b/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_get_hive_database_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetHiveDatabase +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-biglake-hive + + +# [START biglake_v1_generated_HiveMetastoreService_GetHiveDatabase_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import biglake_hive_v1 + + +async def sample_get_hive_database(): + # Create a client + client = biglake_hive_v1.HiveMetastoreServiceAsyncClient() + + # Initialize request argument(s) + request = biglake_hive_v1.GetHiveDatabaseRequest( + name="name_value", + ) + + # Make the request + response = await client.get_hive_database(request=request) + + # Handle the response + print(response) + + +# [END biglake_v1_generated_HiveMetastoreService_GetHiveDatabase_async] diff --git a/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_get_hive_database_sync.py b/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_get_hive_database_sync.py new file mode 100644 index 000000000000..ad26163be057 --- /dev/null +++ b/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_get_hive_database_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetHiveDatabase +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-biglake-hive + + +# [START biglake_v1_generated_HiveMetastoreService_GetHiveDatabase_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import biglake_hive_v1 + + +def sample_get_hive_database(): + # Create a client + client = biglake_hive_v1.HiveMetastoreServiceClient() + + # Initialize request argument(s) + request = biglake_hive_v1.GetHiveDatabaseRequest( + name="name_value", + ) + + # Make the request + response = client.get_hive_database(request=request) + + # Handle the response + print(response) + + +# [END biglake_v1_generated_HiveMetastoreService_GetHiveDatabase_sync] diff --git a/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_get_hive_table_async.py b/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_get_hive_table_async.py new file mode 100644 index 000000000000..6fd6b448d258 --- /dev/null +++ b/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_get_hive_table_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetHiveTable +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-biglake-hive + + +# [START biglake_v1_generated_HiveMetastoreService_GetHiveTable_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import biglake_hive_v1 + + +async def sample_get_hive_table(): + # Create a client + client = biglake_hive_v1.HiveMetastoreServiceAsyncClient() + + # Initialize request argument(s) + request = biglake_hive_v1.GetHiveTableRequest( + name="name_value", + ) + + # Make the request + response = await client.get_hive_table(request=request) + + # Handle the response + print(response) + + +# [END biglake_v1_generated_HiveMetastoreService_GetHiveTable_async] diff --git a/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_get_hive_table_sync.py b/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_get_hive_table_sync.py new file mode 100644 index 000000000000..bfba39fe3cb2 --- /dev/null +++ b/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_get_hive_table_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetHiveTable +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-biglake-hive + + +# [START biglake_v1_generated_HiveMetastoreService_GetHiveTable_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import biglake_hive_v1 + + +def sample_get_hive_table(): + # Create a client + client = biglake_hive_v1.HiveMetastoreServiceClient() + + # Initialize request argument(s) + request = biglake_hive_v1.GetHiveTableRequest( + name="name_value", + ) + + # Make the request + response = client.get_hive_table(request=request) + + # Handle the response + print(response) + + +# [END biglake_v1_generated_HiveMetastoreService_GetHiveTable_sync] diff --git a/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_list_hive_catalogs_async.py b/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_list_hive_catalogs_async.py new file mode 100644 index 000000000000..65967878dd4e --- /dev/null +++ b/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_list_hive_catalogs_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListHiveCatalogs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-biglake-hive + + +# [START biglake_v1_generated_HiveMetastoreService_ListHiveCatalogs_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import biglake_hive_v1 + + +async def sample_list_hive_catalogs(): + # Create a client + client = biglake_hive_v1.HiveMetastoreServiceAsyncClient() + + # Initialize request argument(s) + request = biglake_hive_v1.ListHiveCatalogsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_hive_catalogs(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END biglake_v1_generated_HiveMetastoreService_ListHiveCatalogs_async] diff --git a/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_list_hive_catalogs_sync.py b/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_list_hive_catalogs_sync.py new file mode 100644 index 000000000000..4282d34521a8 --- /dev/null +++ b/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_list_hive_catalogs_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListHiveCatalogs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-biglake-hive + + +# [START biglake_v1_generated_HiveMetastoreService_ListHiveCatalogs_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import biglake_hive_v1 + + +def sample_list_hive_catalogs(): + # Create a client + client = biglake_hive_v1.HiveMetastoreServiceClient() + + # Initialize request argument(s) + request = biglake_hive_v1.ListHiveCatalogsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_hive_catalogs(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END biglake_v1_generated_HiveMetastoreService_ListHiveCatalogs_sync] diff --git a/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_list_hive_databases_async.py b/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_list_hive_databases_async.py new file mode 100644 index 000000000000..fb78cdf11446 --- /dev/null +++ b/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_list_hive_databases_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListHiveDatabases +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-biglake-hive + + +# [START biglake_v1_generated_HiveMetastoreService_ListHiveDatabases_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import biglake_hive_v1 + + +async def sample_list_hive_databases(): + # Create a client + client = biglake_hive_v1.HiveMetastoreServiceAsyncClient() + + # Initialize request argument(s) + request = biglake_hive_v1.ListHiveDatabasesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_hive_databases(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END biglake_v1_generated_HiveMetastoreService_ListHiveDatabases_async] diff --git a/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_list_hive_databases_sync.py b/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_list_hive_databases_sync.py new file mode 100644 index 000000000000..3b2a6fe2b17f --- /dev/null +++ b/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_list_hive_databases_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListHiveDatabases +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-biglake-hive + + +# [START biglake_v1_generated_HiveMetastoreService_ListHiveDatabases_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import biglake_hive_v1 + + +def sample_list_hive_databases(): + # Create a client + client = biglake_hive_v1.HiveMetastoreServiceClient() + + # Initialize request argument(s) + request = biglake_hive_v1.ListHiveDatabasesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_hive_databases(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END biglake_v1_generated_HiveMetastoreService_ListHiveDatabases_sync] diff --git a/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_list_hive_tables_async.py b/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_list_hive_tables_async.py new file mode 100644 index 000000000000..cb452a3fd730 --- /dev/null +++ b/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_list_hive_tables_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListHiveTables +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-biglake-hive + + +# [START biglake_v1_generated_HiveMetastoreService_ListHiveTables_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import biglake_hive_v1 + + +async def sample_list_hive_tables(): + # Create a client + client = biglake_hive_v1.HiveMetastoreServiceAsyncClient() + + # Initialize request argument(s) + request = biglake_hive_v1.ListHiveTablesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_hive_tables(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END biglake_v1_generated_HiveMetastoreService_ListHiveTables_async] diff --git a/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_list_hive_tables_sync.py b/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_list_hive_tables_sync.py new file mode 100644 index 000000000000..786e5c82f2f4 --- /dev/null +++ b/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_list_hive_tables_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListHiveTables +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-biglake-hive + + +# [START biglake_v1_generated_HiveMetastoreService_ListHiveTables_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import biglake_hive_v1 + + +def sample_list_hive_tables(): + # Create a client + client = biglake_hive_v1.HiveMetastoreServiceClient() + + # Initialize request argument(s) + request = biglake_hive_v1.ListHiveTablesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_hive_tables(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END biglake_v1_generated_HiveMetastoreService_ListHiveTables_sync] diff --git a/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_list_partitions_async.py b/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_list_partitions_async.py new file mode 100644 index 000000000000..3eb540ce62be --- /dev/null +++ b/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_list_partitions_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListPartitions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-biglake-hive + + +# [START biglake_v1_generated_HiveMetastoreService_ListPartitions_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import biglake_hive_v1 + + +async def sample_list_partitions(): + # Create a client + client = biglake_hive_v1.HiveMetastoreServiceAsyncClient() + + # Initialize request argument(s) + request = biglake_hive_v1.ListPartitionsRequest( + parent="parent_value", + ) + + # Make the request + stream = await client.list_partitions(request=request) + + # Handle the response + async for response in stream: + print(response) + + +# [END biglake_v1_generated_HiveMetastoreService_ListPartitions_async] diff --git a/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_list_partitions_sync.py b/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_list_partitions_sync.py new file mode 100644 index 000000000000..57cbfb47a960 --- /dev/null +++ b/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_list_partitions_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListPartitions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-biglake-hive + + +# [START biglake_v1_generated_HiveMetastoreService_ListPartitions_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import biglake_hive_v1 + + +def sample_list_partitions(): + # Create a client + client = biglake_hive_v1.HiveMetastoreServiceClient() + + # Initialize request argument(s) + request = biglake_hive_v1.ListPartitionsRequest( + parent="parent_value", + ) + + # Make the request + stream = client.list_partitions(request=request) + + # Handle the response + for response in stream: + print(response) + + +# [END biglake_v1_generated_HiveMetastoreService_ListPartitions_sync] diff --git a/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_update_hive_catalog_async.py b/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_update_hive_catalog_async.py new file mode 100644 index 000000000000..328b19ef3a1b --- /dev/null +++ b/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_update_hive_catalog_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateHiveCatalog +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-biglake-hive + + +# [START biglake_v1_generated_HiveMetastoreService_UpdateHiveCatalog_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import biglake_hive_v1 + + +async def sample_update_hive_catalog(): + # Create a client + client = biglake_hive_v1.HiveMetastoreServiceAsyncClient() + + # Initialize request argument(s) + hive_catalog = biglake_hive_v1.HiveCatalog() + hive_catalog.location_uri = "location_uri_value" + + request = biglake_hive_v1.UpdateHiveCatalogRequest( + hive_catalog=hive_catalog, + ) + + # Make the request + response = await client.update_hive_catalog(request=request) + + # Handle the response + print(response) + + +# [END biglake_v1_generated_HiveMetastoreService_UpdateHiveCatalog_async] diff --git a/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_update_hive_catalog_sync.py b/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_update_hive_catalog_sync.py new file mode 100644 index 000000000000..18b2cafe5771 --- /dev/null +++ b/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_update_hive_catalog_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateHiveCatalog +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-biglake-hive + + +# [START biglake_v1_generated_HiveMetastoreService_UpdateHiveCatalog_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import biglake_hive_v1 + + +def sample_update_hive_catalog(): + # Create a client + client = biglake_hive_v1.HiveMetastoreServiceClient() + + # Initialize request argument(s) + hive_catalog = biglake_hive_v1.HiveCatalog() + hive_catalog.location_uri = "location_uri_value" + + request = biglake_hive_v1.UpdateHiveCatalogRequest( + hive_catalog=hive_catalog, + ) + + # Make the request + response = client.update_hive_catalog(request=request) + + # Handle the response + print(response) + + +# [END biglake_v1_generated_HiveMetastoreService_UpdateHiveCatalog_sync] diff --git a/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_update_hive_database_async.py b/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_update_hive_database_async.py new file mode 100644 index 000000000000..1716087b1070 --- /dev/null +++ b/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_update_hive_database_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateHiveDatabase +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-biglake-hive + + +# [START biglake_v1_generated_HiveMetastoreService_UpdateHiveDatabase_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import biglake_hive_v1 + + +async def sample_update_hive_database(): + # Create a client + client = biglake_hive_v1.HiveMetastoreServiceAsyncClient() + + # Initialize request argument(s) + request = biglake_hive_v1.UpdateHiveDatabaseRequest() + + # Make the request + response = await client.update_hive_database(request=request) + + # Handle the response + print(response) + + +# [END biglake_v1_generated_HiveMetastoreService_UpdateHiveDatabase_async] diff --git a/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_update_hive_database_sync.py b/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_update_hive_database_sync.py new file mode 100644 index 000000000000..7df12e6da206 --- /dev/null +++ b/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_update_hive_database_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateHiveDatabase +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-biglake-hive + + +# [START biglake_v1_generated_HiveMetastoreService_UpdateHiveDatabase_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import biglake_hive_v1 + + +def sample_update_hive_database(): + # Create a client + client = biglake_hive_v1.HiveMetastoreServiceClient() + + # Initialize request argument(s) + request = biglake_hive_v1.UpdateHiveDatabaseRequest() + + # Make the request + response = client.update_hive_database(request=request) + + # Handle the response + print(response) + + +# [END biglake_v1_generated_HiveMetastoreService_UpdateHiveDatabase_sync] diff --git a/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_update_hive_table_async.py b/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_update_hive_table_async.py new file mode 100644 index 000000000000..f676ab094b85 --- /dev/null +++ b/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_update_hive_table_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateHiveTable +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-biglake-hive + + +# [START biglake_v1_generated_HiveMetastoreService_UpdateHiveTable_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import biglake_hive_v1 + + +async def sample_update_hive_table(): + # Create a client + client = biglake_hive_v1.HiveMetastoreServiceAsyncClient() + + # Initialize request argument(s) + hive_table = biglake_hive_v1.HiveTable() + hive_table.storage_descriptor.columns.name = "name_value" + hive_table.storage_descriptor.columns.type_ = "type__value" + + request = biglake_hive_v1.UpdateHiveTableRequest( + hive_table=hive_table, + ) + + # Make the request + response = await client.update_hive_table(request=request) + + # Handle the response + print(response) + + +# [END biglake_v1_generated_HiveMetastoreService_UpdateHiveTable_async] diff --git a/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_update_hive_table_sync.py b/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_update_hive_table_sync.py new file mode 100644 index 000000000000..4da9687cd7c2 --- /dev/null +++ b/packages/google-cloud-biglake-hive/samples/generated_samples/biglake_v1_generated_hive_metastore_service_update_hive_table_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateHiveTable +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-biglake-hive + + +# [START biglake_v1_generated_HiveMetastoreService_UpdateHiveTable_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import biglake_hive_v1 + + +def sample_update_hive_table(): + # Create a client + client = biglake_hive_v1.HiveMetastoreServiceClient() + + # Initialize request argument(s) + hive_table = biglake_hive_v1.HiveTable() + hive_table.storage_descriptor.columns.name = "name_value" + hive_table.storage_descriptor.columns.type_ = "type__value" + + request = biglake_hive_v1.UpdateHiveTableRequest( + hive_table=hive_table, + ) + + # Make the request + response = client.update_hive_table(request=request) + + # Handle the response + print(response) + + +# [END biglake_v1_generated_HiveMetastoreService_UpdateHiveTable_sync] diff --git a/packages/google-cloud-biglake-hive/samples/generated_samples/snippet_metadata_google.cloud.biglake.hive.v1.json b/packages/google-cloud-biglake-hive/samples/generated_samples/snippet_metadata_google.cloud.biglake.hive.v1.json new file mode 100644 index 000000000000..f441c6badc16 --- /dev/null +++ b/packages/google-cloud-biglake-hive/samples/generated_samples/snippet_metadata_google.cloud.biglake.hive.v1.json @@ -0,0 +1,3291 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.cloud.biglake.hive.v1", + "version": "v1" + } + ], + "language": "PYTHON", + "name": "google-cloud-biglake-hive", + "version": "0.3.2" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.biglake_hive_v1.HiveMetastoreServiceAsyncClient", + "shortName": "HiveMetastoreServiceAsyncClient" + }, + "fullName": "google.cloud.biglake_hive_v1.HiveMetastoreServiceAsyncClient.batch_create_partitions", + "method": { + "fullName": "google.cloud.biglake.hive.v1.HiveMetastoreService.BatchCreatePartitions", + "service": { + "fullName": "google.cloud.biglake.hive.v1.HiveMetastoreService", + "shortName": "HiveMetastoreService" + }, + "shortName": "BatchCreatePartitions" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.biglake_hive_v1.types.BatchCreatePartitionsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.biglake_hive_v1.types.BatchCreatePartitionsResponse", + "shortName": "batch_create_partitions" + }, + "description": "Sample for BatchCreatePartitions", + "file": "biglake_v1_generated_hive_metastore_service_batch_create_partitions_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "biglake_v1_generated_HiveMetastoreService_BatchCreatePartitions_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "biglake_v1_generated_hive_metastore_service_batch_create_partitions_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.biglake_hive_v1.HiveMetastoreServiceClient", + "shortName": "HiveMetastoreServiceClient" + }, + "fullName": "google.cloud.biglake_hive_v1.HiveMetastoreServiceClient.batch_create_partitions", + "method": { + "fullName": "google.cloud.biglake.hive.v1.HiveMetastoreService.BatchCreatePartitions", + "service": { + "fullName": "google.cloud.biglake.hive.v1.HiveMetastoreService", + "shortName": "HiveMetastoreService" + }, + "shortName": "BatchCreatePartitions" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.biglake_hive_v1.types.BatchCreatePartitionsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.biglake_hive_v1.types.BatchCreatePartitionsResponse", + "shortName": "batch_create_partitions" + }, + "description": "Sample for BatchCreatePartitions", + "file": "biglake_v1_generated_hive_metastore_service_batch_create_partitions_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "biglake_v1_generated_HiveMetastoreService_BatchCreatePartitions_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "biglake_v1_generated_hive_metastore_service_batch_create_partitions_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.biglake_hive_v1.HiveMetastoreServiceAsyncClient", + "shortName": "HiveMetastoreServiceAsyncClient" + }, + "fullName": "google.cloud.biglake_hive_v1.HiveMetastoreServiceAsyncClient.batch_delete_partitions", + "method": { + "fullName": "google.cloud.biglake.hive.v1.HiveMetastoreService.BatchDeletePartitions", + "service": { + "fullName": "google.cloud.biglake.hive.v1.HiveMetastoreService", + "shortName": "HiveMetastoreService" + }, + "shortName": "BatchDeletePartitions" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.biglake_hive_v1.types.BatchDeletePartitionsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "shortName": "batch_delete_partitions" + }, + "description": "Sample for BatchDeletePartitions", + "file": "biglake_v1_generated_hive_metastore_service_batch_delete_partitions_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "biglake_v1_generated_HiveMetastoreService_BatchDeletePartitions_async", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "biglake_v1_generated_hive_metastore_service_batch_delete_partitions_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.biglake_hive_v1.HiveMetastoreServiceClient", + "shortName": "HiveMetastoreServiceClient" + }, + "fullName": "google.cloud.biglake_hive_v1.HiveMetastoreServiceClient.batch_delete_partitions", + "method": { + "fullName": "google.cloud.biglake.hive.v1.HiveMetastoreService.BatchDeletePartitions", + "service": { + "fullName": "google.cloud.biglake.hive.v1.HiveMetastoreService", + "shortName": "HiveMetastoreService" + }, + "shortName": "BatchDeletePartitions" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.biglake_hive_v1.types.BatchDeletePartitionsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "shortName": "batch_delete_partitions" + }, + "description": "Sample for BatchDeletePartitions", + "file": "biglake_v1_generated_hive_metastore_service_batch_delete_partitions_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "biglake_v1_generated_HiveMetastoreService_BatchDeletePartitions_sync", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "biglake_v1_generated_hive_metastore_service_batch_delete_partitions_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.biglake_hive_v1.HiveMetastoreServiceAsyncClient", + "shortName": "HiveMetastoreServiceAsyncClient" + }, + "fullName": "google.cloud.biglake_hive_v1.HiveMetastoreServiceAsyncClient.batch_update_partitions", + "method": { + "fullName": "google.cloud.biglake.hive.v1.HiveMetastoreService.BatchUpdatePartitions", + "service": { + "fullName": "google.cloud.biglake.hive.v1.HiveMetastoreService", + "shortName": "HiveMetastoreService" + }, + "shortName": "BatchUpdatePartitions" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.biglake_hive_v1.types.BatchUpdatePartitionsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.biglake_hive_v1.types.BatchUpdatePartitionsResponse", + "shortName": "batch_update_partitions" + }, + "description": "Sample for BatchUpdatePartitions", + "file": "biglake_v1_generated_hive_metastore_service_batch_update_partitions_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "biglake_v1_generated_HiveMetastoreService_BatchUpdatePartitions_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "biglake_v1_generated_hive_metastore_service_batch_update_partitions_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.biglake_hive_v1.HiveMetastoreServiceClient", + "shortName": "HiveMetastoreServiceClient" + }, + "fullName": "google.cloud.biglake_hive_v1.HiveMetastoreServiceClient.batch_update_partitions", + "method": { + "fullName": "google.cloud.biglake.hive.v1.HiveMetastoreService.BatchUpdatePartitions", + "service": { + "fullName": "google.cloud.biglake.hive.v1.HiveMetastoreService", + "shortName": "HiveMetastoreService" + }, + "shortName": "BatchUpdatePartitions" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.biglake_hive_v1.types.BatchUpdatePartitionsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.biglake_hive_v1.types.BatchUpdatePartitionsResponse", + "shortName": "batch_update_partitions" + }, + "description": "Sample for BatchUpdatePartitions", + "file": "biglake_v1_generated_hive_metastore_service_batch_update_partitions_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "biglake_v1_generated_HiveMetastoreService_BatchUpdatePartitions_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "biglake_v1_generated_hive_metastore_service_batch_update_partitions_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.biglake_hive_v1.HiveMetastoreServiceAsyncClient", + "shortName": "HiveMetastoreServiceAsyncClient" + }, + "fullName": "google.cloud.biglake_hive_v1.HiveMetastoreServiceAsyncClient.create_hive_catalog", + "method": { + "fullName": "google.cloud.biglake.hive.v1.HiveMetastoreService.CreateHiveCatalog", + "service": { + "fullName": "google.cloud.biglake.hive.v1.HiveMetastoreService", + "shortName": "HiveMetastoreService" + }, + "shortName": "CreateHiveCatalog" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.biglake_hive_v1.types.CreateHiveCatalogRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "hive_catalog", + "type": "google.cloud.biglake_hive_v1.types.HiveCatalog" + }, + { + "name": "hive_catalog_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.biglake_hive_v1.types.HiveCatalog", + "shortName": "create_hive_catalog" + }, + "description": "Sample for CreateHiveCatalog", + "file": "biglake_v1_generated_hive_metastore_service_create_hive_catalog_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "biglake_v1_generated_HiveMetastoreService_CreateHiveCatalog_async", + "segments": [ + { + "end": 57, + "start": 27, + "type": "FULL" + }, + { + "end": 57, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 51, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 54, + "start": 52, + "type": "REQUEST_EXECUTION" + }, + { + "end": 58, + "start": 55, + "type": "RESPONSE_HANDLING" + } + ], + "title": "biglake_v1_generated_hive_metastore_service_create_hive_catalog_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.biglake_hive_v1.HiveMetastoreServiceClient", + "shortName": "HiveMetastoreServiceClient" + }, + "fullName": "google.cloud.biglake_hive_v1.HiveMetastoreServiceClient.create_hive_catalog", + "method": { + "fullName": "google.cloud.biglake.hive.v1.HiveMetastoreService.CreateHiveCatalog", + "service": { + "fullName": "google.cloud.biglake.hive.v1.HiveMetastoreService", + "shortName": "HiveMetastoreService" + }, + "shortName": "CreateHiveCatalog" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.biglake_hive_v1.types.CreateHiveCatalogRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "hive_catalog", + "type": "google.cloud.biglake_hive_v1.types.HiveCatalog" + }, + { + "name": "hive_catalog_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.biglake_hive_v1.types.HiveCatalog", + "shortName": "create_hive_catalog" + }, + "description": "Sample for CreateHiveCatalog", + "file": "biglake_v1_generated_hive_metastore_service_create_hive_catalog_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "biglake_v1_generated_HiveMetastoreService_CreateHiveCatalog_sync", + "segments": [ + { + "end": 57, + "start": 27, + "type": "FULL" + }, + { + "end": 57, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 51, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 54, + "start": 52, + "type": "REQUEST_EXECUTION" + }, + { + "end": 58, + "start": 55, + "type": "RESPONSE_HANDLING" + } + ], + "title": "biglake_v1_generated_hive_metastore_service_create_hive_catalog_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.biglake_hive_v1.HiveMetastoreServiceAsyncClient", + "shortName": "HiveMetastoreServiceAsyncClient" + }, + "fullName": "google.cloud.biglake_hive_v1.HiveMetastoreServiceAsyncClient.create_hive_database", + "method": { + "fullName": "google.cloud.biglake.hive.v1.HiveMetastoreService.CreateHiveDatabase", + "service": { + "fullName": "google.cloud.biglake.hive.v1.HiveMetastoreService", + "shortName": "HiveMetastoreService" + }, + "shortName": "CreateHiveDatabase" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.biglake_hive_v1.types.CreateHiveDatabaseRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "hive_database", + "type": "google.cloud.biglake_hive_v1.types.HiveDatabase" + }, + { + "name": "hive_database_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.biglake_hive_v1.types.HiveDatabase", + "shortName": "create_hive_database" + }, + "description": "Sample for CreateHiveDatabase", + "file": "biglake_v1_generated_hive_metastore_service_create_hive_database_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "biglake_v1_generated_HiveMetastoreService_CreateHiveDatabase_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "biglake_v1_generated_hive_metastore_service_create_hive_database_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.biglake_hive_v1.HiveMetastoreServiceClient", + "shortName": "HiveMetastoreServiceClient" + }, + "fullName": "google.cloud.biglake_hive_v1.HiveMetastoreServiceClient.create_hive_database", + "method": { + "fullName": "google.cloud.biglake.hive.v1.HiveMetastoreService.CreateHiveDatabase", + "service": { + "fullName": "google.cloud.biglake.hive.v1.HiveMetastoreService", + "shortName": "HiveMetastoreService" + }, + "shortName": "CreateHiveDatabase" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.biglake_hive_v1.types.CreateHiveDatabaseRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "hive_database", + "type": "google.cloud.biglake_hive_v1.types.HiveDatabase" + }, + { + "name": "hive_database_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.biglake_hive_v1.types.HiveDatabase", + "shortName": "create_hive_database" + }, + "description": "Sample for CreateHiveDatabase", + "file": "biglake_v1_generated_hive_metastore_service_create_hive_database_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "biglake_v1_generated_HiveMetastoreService_CreateHiveDatabase_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "biglake_v1_generated_hive_metastore_service_create_hive_database_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.biglake_hive_v1.HiveMetastoreServiceAsyncClient", + "shortName": "HiveMetastoreServiceAsyncClient" + }, + "fullName": "google.cloud.biglake_hive_v1.HiveMetastoreServiceAsyncClient.create_hive_table", + "method": { + "fullName": "google.cloud.biglake.hive.v1.HiveMetastoreService.CreateHiveTable", + "service": { + "fullName": "google.cloud.biglake.hive.v1.HiveMetastoreService", + "shortName": "HiveMetastoreService" + }, + "shortName": "CreateHiveTable" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.biglake_hive_v1.types.CreateHiveTableRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "hive_table", + "type": "google.cloud.biglake_hive_v1.types.HiveTable" + }, + { + "name": "hive_table_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.biglake_hive_v1.types.HiveTable", + "shortName": "create_hive_table" + }, + "description": "Sample for CreateHiveTable", + "file": "biglake_v1_generated_hive_metastore_service_create_hive_table_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "biglake_v1_generated_HiveMetastoreService_CreateHiveTable_async", + "segments": [ + { + "end": 57, + "start": 27, + "type": "FULL" + }, + { + "end": 57, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 51, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 54, + "start": 52, + "type": "REQUEST_EXECUTION" + }, + { + "end": 58, + "start": 55, + "type": "RESPONSE_HANDLING" + } + ], + "title": "biglake_v1_generated_hive_metastore_service_create_hive_table_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.biglake_hive_v1.HiveMetastoreServiceClient", + "shortName": "HiveMetastoreServiceClient" + }, + "fullName": "google.cloud.biglake_hive_v1.HiveMetastoreServiceClient.create_hive_table", + "method": { + "fullName": "google.cloud.biglake.hive.v1.HiveMetastoreService.CreateHiveTable", + "service": { + "fullName": "google.cloud.biglake.hive.v1.HiveMetastoreService", + "shortName": "HiveMetastoreService" + }, + "shortName": "CreateHiveTable" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.biglake_hive_v1.types.CreateHiveTableRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "hive_table", + "type": "google.cloud.biglake_hive_v1.types.HiveTable" + }, + { + "name": "hive_table_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.biglake_hive_v1.types.HiveTable", + "shortName": "create_hive_table" + }, + "description": "Sample for CreateHiveTable", + "file": "biglake_v1_generated_hive_metastore_service_create_hive_table_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "biglake_v1_generated_HiveMetastoreService_CreateHiveTable_sync", + "segments": [ + { + "end": 57, + "start": 27, + "type": "FULL" + }, + { + "end": 57, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 51, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 54, + "start": 52, + "type": "REQUEST_EXECUTION" + }, + { + "end": 58, + "start": 55, + "type": "RESPONSE_HANDLING" + } + ], + "title": "biglake_v1_generated_hive_metastore_service_create_hive_table_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.biglake_hive_v1.HiveMetastoreServiceAsyncClient", + "shortName": "HiveMetastoreServiceAsyncClient" + }, + "fullName": "google.cloud.biglake_hive_v1.HiveMetastoreServiceAsyncClient.delete_hive_catalog", + "method": { + "fullName": "google.cloud.biglake.hive.v1.HiveMetastoreService.DeleteHiveCatalog", + "service": { + "fullName": "google.cloud.biglake.hive.v1.HiveMetastoreService", + "shortName": "HiveMetastoreService" + }, + "shortName": "DeleteHiveCatalog" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.biglake_hive_v1.types.DeleteHiveCatalogRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "shortName": "delete_hive_catalog" + }, + "description": "Sample for DeleteHiveCatalog", + "file": "biglake_v1_generated_hive_metastore_service_delete_hive_catalog_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "biglake_v1_generated_HiveMetastoreService_DeleteHiveCatalog_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "biglake_v1_generated_hive_metastore_service_delete_hive_catalog_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.biglake_hive_v1.HiveMetastoreServiceClient", + "shortName": "HiveMetastoreServiceClient" + }, + "fullName": "google.cloud.biglake_hive_v1.HiveMetastoreServiceClient.delete_hive_catalog", + "method": { + "fullName": "google.cloud.biglake.hive.v1.HiveMetastoreService.DeleteHiveCatalog", + "service": { + "fullName": "google.cloud.biglake.hive.v1.HiveMetastoreService", + "shortName": "HiveMetastoreService" + }, + "shortName": "DeleteHiveCatalog" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.biglake_hive_v1.types.DeleteHiveCatalogRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "shortName": "delete_hive_catalog" + }, + "description": "Sample for DeleteHiveCatalog", + "file": "biglake_v1_generated_hive_metastore_service_delete_hive_catalog_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "biglake_v1_generated_HiveMetastoreService_DeleteHiveCatalog_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "biglake_v1_generated_hive_metastore_service_delete_hive_catalog_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.biglake_hive_v1.HiveMetastoreServiceAsyncClient", + "shortName": "HiveMetastoreServiceAsyncClient" + }, + "fullName": "google.cloud.biglake_hive_v1.HiveMetastoreServiceAsyncClient.delete_hive_database", + "method": { + "fullName": "google.cloud.biglake.hive.v1.HiveMetastoreService.DeleteHiveDatabase", + "service": { + "fullName": "google.cloud.biglake.hive.v1.HiveMetastoreService", + "shortName": "HiveMetastoreService" + }, + "shortName": "DeleteHiveDatabase" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.biglake_hive_v1.types.DeleteHiveDatabaseRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "shortName": "delete_hive_database" + }, + "description": "Sample for DeleteHiveDatabase", + "file": "biglake_v1_generated_hive_metastore_service_delete_hive_database_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "biglake_v1_generated_HiveMetastoreService_DeleteHiveDatabase_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "biglake_v1_generated_hive_metastore_service_delete_hive_database_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.biglake_hive_v1.HiveMetastoreServiceClient", + "shortName": "HiveMetastoreServiceClient" + }, + "fullName": "google.cloud.biglake_hive_v1.HiveMetastoreServiceClient.delete_hive_database", + "method": { + "fullName": "google.cloud.biglake.hive.v1.HiveMetastoreService.DeleteHiveDatabase", + "service": { + "fullName": "google.cloud.biglake.hive.v1.HiveMetastoreService", + "shortName": "HiveMetastoreService" + }, + "shortName": "DeleteHiveDatabase" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.biglake_hive_v1.types.DeleteHiveDatabaseRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "shortName": "delete_hive_database" + }, + "description": "Sample for DeleteHiveDatabase", + "file": "biglake_v1_generated_hive_metastore_service_delete_hive_database_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "biglake_v1_generated_HiveMetastoreService_DeleteHiveDatabase_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "biglake_v1_generated_hive_metastore_service_delete_hive_database_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.biglake_hive_v1.HiveMetastoreServiceAsyncClient", + "shortName": "HiveMetastoreServiceAsyncClient" + }, + "fullName": "google.cloud.biglake_hive_v1.HiveMetastoreServiceAsyncClient.delete_hive_table", + "method": { + "fullName": "google.cloud.biglake.hive.v1.HiveMetastoreService.DeleteHiveTable", + "service": { + "fullName": "google.cloud.biglake.hive.v1.HiveMetastoreService", + "shortName": "HiveMetastoreService" + }, + "shortName": "DeleteHiveTable" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.biglake_hive_v1.types.DeleteHiveTableRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "shortName": "delete_hive_table" + }, + "description": "Sample for DeleteHiveTable", + "file": "biglake_v1_generated_hive_metastore_service_delete_hive_table_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "biglake_v1_generated_HiveMetastoreService_DeleteHiveTable_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "biglake_v1_generated_hive_metastore_service_delete_hive_table_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.biglake_hive_v1.HiveMetastoreServiceClient", + "shortName": "HiveMetastoreServiceClient" + }, + "fullName": "google.cloud.biglake_hive_v1.HiveMetastoreServiceClient.delete_hive_table", + "method": { + "fullName": "google.cloud.biglake.hive.v1.HiveMetastoreService.DeleteHiveTable", + "service": { + "fullName": "google.cloud.biglake.hive.v1.HiveMetastoreService", + "shortName": "HiveMetastoreService" + }, + "shortName": "DeleteHiveTable" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.biglake_hive_v1.types.DeleteHiveTableRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "shortName": "delete_hive_table" + }, + "description": "Sample for DeleteHiveTable", + "file": "biglake_v1_generated_hive_metastore_service_delete_hive_table_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "biglake_v1_generated_HiveMetastoreService_DeleteHiveTable_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "biglake_v1_generated_hive_metastore_service_delete_hive_table_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.biglake_hive_v1.HiveMetastoreServiceAsyncClient", + "shortName": "HiveMetastoreServiceAsyncClient" + }, + "fullName": "google.cloud.biglake_hive_v1.HiveMetastoreServiceAsyncClient.failover_hive_catalog", + "method": { + "fullName": "google.cloud.biglake.hive.v1.HiveMetastoreService.FailoverHiveCatalog", + "service": { + "fullName": "google.cloud.biglake.hive.v1.HiveMetastoreService", + "shortName": "HiveMetastoreService" + }, + "shortName": "FailoverHiveCatalog" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.biglake_hive_v1.types.FailoverHiveCatalogRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "primary_replica", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.biglake_hive_v1.types.FailoverHiveCatalogResponse", + "shortName": "failover_hive_catalog" + }, + "description": "Sample for FailoverHiveCatalog", + "file": "biglake_v1_generated_hive_metastore_service_failover_hive_catalog_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "biglake_v1_generated_HiveMetastoreService_FailoverHiveCatalog_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "biglake_v1_generated_hive_metastore_service_failover_hive_catalog_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.biglake_hive_v1.HiveMetastoreServiceClient", + "shortName": "HiveMetastoreServiceClient" + }, + "fullName": "google.cloud.biglake_hive_v1.HiveMetastoreServiceClient.failover_hive_catalog", + "method": { + "fullName": "google.cloud.biglake.hive.v1.HiveMetastoreService.FailoverHiveCatalog", + "service": { + "fullName": "google.cloud.biglake.hive.v1.HiveMetastoreService", + "shortName": "HiveMetastoreService" + }, + "shortName": "FailoverHiveCatalog" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.biglake_hive_v1.types.FailoverHiveCatalogRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "primary_replica", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.biglake_hive_v1.types.FailoverHiveCatalogResponse", + "shortName": "failover_hive_catalog" + }, + "description": "Sample for FailoverHiveCatalog", + "file": "biglake_v1_generated_hive_metastore_service_failover_hive_catalog_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "biglake_v1_generated_HiveMetastoreService_FailoverHiveCatalog_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "biglake_v1_generated_hive_metastore_service_failover_hive_catalog_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.biglake_hive_v1.HiveMetastoreServiceAsyncClient", + "shortName": "HiveMetastoreServiceAsyncClient" + }, + "fullName": "google.cloud.biglake_hive_v1.HiveMetastoreServiceAsyncClient.get_hive_catalog", + "method": { + "fullName": "google.cloud.biglake.hive.v1.HiveMetastoreService.GetHiveCatalog", + "service": { + "fullName": "google.cloud.biglake.hive.v1.HiveMetastoreService", + "shortName": "HiveMetastoreService" + }, + "shortName": "GetHiveCatalog" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.biglake_hive_v1.types.GetHiveCatalogRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.biglake_hive_v1.types.HiveCatalog", + "shortName": "get_hive_catalog" + }, + "description": "Sample for GetHiveCatalog", + "file": "biglake_v1_generated_hive_metastore_service_get_hive_catalog_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "biglake_v1_generated_HiveMetastoreService_GetHiveCatalog_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "biglake_v1_generated_hive_metastore_service_get_hive_catalog_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.biglake_hive_v1.HiveMetastoreServiceClient", + "shortName": "HiveMetastoreServiceClient" + }, + "fullName": "google.cloud.biglake_hive_v1.HiveMetastoreServiceClient.get_hive_catalog", + "method": { + "fullName": "google.cloud.biglake.hive.v1.HiveMetastoreService.GetHiveCatalog", + "service": { + "fullName": "google.cloud.biglake.hive.v1.HiveMetastoreService", + "shortName": "HiveMetastoreService" + }, + "shortName": "GetHiveCatalog" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.biglake_hive_v1.types.GetHiveCatalogRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.biglake_hive_v1.types.HiveCatalog", + "shortName": "get_hive_catalog" + }, + "description": "Sample for GetHiveCatalog", + "file": "biglake_v1_generated_hive_metastore_service_get_hive_catalog_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "biglake_v1_generated_HiveMetastoreService_GetHiveCatalog_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "biglake_v1_generated_hive_metastore_service_get_hive_catalog_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.biglake_hive_v1.HiveMetastoreServiceAsyncClient", + "shortName": "HiveMetastoreServiceAsyncClient" + }, + "fullName": "google.cloud.biglake_hive_v1.HiveMetastoreServiceAsyncClient.get_hive_database", + "method": { + "fullName": "google.cloud.biglake.hive.v1.HiveMetastoreService.GetHiveDatabase", + "service": { + "fullName": "google.cloud.biglake.hive.v1.HiveMetastoreService", + "shortName": "HiveMetastoreService" + }, + "shortName": "GetHiveDatabase" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.biglake_hive_v1.types.GetHiveDatabaseRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.biglake_hive_v1.types.HiveDatabase", + "shortName": "get_hive_database" + }, + "description": "Sample for GetHiveDatabase", + "file": "biglake_v1_generated_hive_metastore_service_get_hive_database_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "biglake_v1_generated_HiveMetastoreService_GetHiveDatabase_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "biglake_v1_generated_hive_metastore_service_get_hive_database_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.biglake_hive_v1.HiveMetastoreServiceClient", + "shortName": "HiveMetastoreServiceClient" + }, + "fullName": "google.cloud.biglake_hive_v1.HiveMetastoreServiceClient.get_hive_database", + "method": { + "fullName": "google.cloud.biglake.hive.v1.HiveMetastoreService.GetHiveDatabase", + "service": { + "fullName": "google.cloud.biglake.hive.v1.HiveMetastoreService", + "shortName": "HiveMetastoreService" + }, + "shortName": "GetHiveDatabase" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.biglake_hive_v1.types.GetHiveDatabaseRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.biglake_hive_v1.types.HiveDatabase", + "shortName": "get_hive_database" + }, + "description": "Sample for GetHiveDatabase", + "file": "biglake_v1_generated_hive_metastore_service_get_hive_database_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "biglake_v1_generated_HiveMetastoreService_GetHiveDatabase_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "biglake_v1_generated_hive_metastore_service_get_hive_database_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.biglake_hive_v1.HiveMetastoreServiceAsyncClient", + "shortName": "HiveMetastoreServiceAsyncClient" + }, + "fullName": "google.cloud.biglake_hive_v1.HiveMetastoreServiceAsyncClient.get_hive_table", + "method": { + "fullName": "google.cloud.biglake.hive.v1.HiveMetastoreService.GetHiveTable", + "service": { + "fullName": "google.cloud.biglake.hive.v1.HiveMetastoreService", + "shortName": "HiveMetastoreService" + }, + "shortName": "GetHiveTable" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.biglake_hive_v1.types.GetHiveTableRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.biglake_hive_v1.types.HiveTable", + "shortName": "get_hive_table" + }, + "description": "Sample for GetHiveTable", + "file": "biglake_v1_generated_hive_metastore_service_get_hive_table_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "biglake_v1_generated_HiveMetastoreService_GetHiveTable_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "biglake_v1_generated_hive_metastore_service_get_hive_table_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.biglake_hive_v1.HiveMetastoreServiceClient", + "shortName": "HiveMetastoreServiceClient" + }, + "fullName": "google.cloud.biglake_hive_v1.HiveMetastoreServiceClient.get_hive_table", + "method": { + "fullName": "google.cloud.biglake.hive.v1.HiveMetastoreService.GetHiveTable", + "service": { + "fullName": "google.cloud.biglake.hive.v1.HiveMetastoreService", + "shortName": "HiveMetastoreService" + }, + "shortName": "GetHiveTable" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.biglake_hive_v1.types.GetHiveTableRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.biglake_hive_v1.types.HiveTable", + "shortName": "get_hive_table" + }, + "description": "Sample for GetHiveTable", + "file": "biglake_v1_generated_hive_metastore_service_get_hive_table_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "biglake_v1_generated_HiveMetastoreService_GetHiveTable_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "biglake_v1_generated_hive_metastore_service_get_hive_table_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.biglake_hive_v1.HiveMetastoreServiceAsyncClient", + "shortName": "HiveMetastoreServiceAsyncClient" + }, + "fullName": "google.cloud.biglake_hive_v1.HiveMetastoreServiceAsyncClient.list_hive_catalogs", + "method": { + "fullName": "google.cloud.biglake.hive.v1.HiveMetastoreService.ListHiveCatalogs", + "service": { + "fullName": "google.cloud.biglake.hive.v1.HiveMetastoreService", + "shortName": "HiveMetastoreService" + }, + "shortName": "ListHiveCatalogs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.biglake_hive_v1.types.ListHiveCatalogsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.biglake_hive_v1.services.hive_metastore_service.pagers.ListHiveCatalogsAsyncPager", + "shortName": "list_hive_catalogs" + }, + "description": "Sample for ListHiveCatalogs", + "file": "biglake_v1_generated_hive_metastore_service_list_hive_catalogs_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "biglake_v1_generated_HiveMetastoreService_ListHiveCatalogs_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "biglake_v1_generated_hive_metastore_service_list_hive_catalogs_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.biglake_hive_v1.HiveMetastoreServiceClient", + "shortName": "HiveMetastoreServiceClient" + }, + "fullName": "google.cloud.biglake_hive_v1.HiveMetastoreServiceClient.list_hive_catalogs", + "method": { + "fullName": "google.cloud.biglake.hive.v1.HiveMetastoreService.ListHiveCatalogs", + "service": { + "fullName": "google.cloud.biglake.hive.v1.HiveMetastoreService", + "shortName": "HiveMetastoreService" + }, + "shortName": "ListHiveCatalogs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.biglake_hive_v1.types.ListHiveCatalogsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.biglake_hive_v1.services.hive_metastore_service.pagers.ListHiveCatalogsPager", + "shortName": "list_hive_catalogs" + }, + "description": "Sample for ListHiveCatalogs", + "file": "biglake_v1_generated_hive_metastore_service_list_hive_catalogs_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "biglake_v1_generated_HiveMetastoreService_ListHiveCatalogs_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "biglake_v1_generated_hive_metastore_service_list_hive_catalogs_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.biglake_hive_v1.HiveMetastoreServiceAsyncClient", + "shortName": "HiveMetastoreServiceAsyncClient" + }, + "fullName": "google.cloud.biglake_hive_v1.HiveMetastoreServiceAsyncClient.list_hive_databases", + "method": { + "fullName": "google.cloud.biglake.hive.v1.HiveMetastoreService.ListHiveDatabases", + "service": { + "fullName": "google.cloud.biglake.hive.v1.HiveMetastoreService", + "shortName": "HiveMetastoreService" + }, + "shortName": "ListHiveDatabases" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.biglake_hive_v1.types.ListHiveDatabasesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.biglake_hive_v1.services.hive_metastore_service.pagers.ListHiveDatabasesAsyncPager", + "shortName": "list_hive_databases" + }, + "description": "Sample for ListHiveDatabases", + "file": "biglake_v1_generated_hive_metastore_service_list_hive_databases_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "biglake_v1_generated_HiveMetastoreService_ListHiveDatabases_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "biglake_v1_generated_hive_metastore_service_list_hive_databases_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.biglake_hive_v1.HiveMetastoreServiceClient", + "shortName": "HiveMetastoreServiceClient" + }, + "fullName": "google.cloud.biglake_hive_v1.HiveMetastoreServiceClient.list_hive_databases", + "method": { + "fullName": "google.cloud.biglake.hive.v1.HiveMetastoreService.ListHiveDatabases", + "service": { + "fullName": "google.cloud.biglake.hive.v1.HiveMetastoreService", + "shortName": "HiveMetastoreService" + }, + "shortName": "ListHiveDatabases" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.biglake_hive_v1.types.ListHiveDatabasesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.biglake_hive_v1.services.hive_metastore_service.pagers.ListHiveDatabasesPager", + "shortName": "list_hive_databases" + }, + "description": "Sample for ListHiveDatabases", + "file": "biglake_v1_generated_hive_metastore_service_list_hive_databases_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "biglake_v1_generated_HiveMetastoreService_ListHiveDatabases_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "biglake_v1_generated_hive_metastore_service_list_hive_databases_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.biglake_hive_v1.HiveMetastoreServiceAsyncClient", + "shortName": "HiveMetastoreServiceAsyncClient" + }, + "fullName": "google.cloud.biglake_hive_v1.HiveMetastoreServiceAsyncClient.list_hive_tables", + "method": { + "fullName": "google.cloud.biglake.hive.v1.HiveMetastoreService.ListHiveTables", + "service": { + "fullName": "google.cloud.biglake.hive.v1.HiveMetastoreService", + "shortName": "HiveMetastoreService" + }, + "shortName": "ListHiveTables" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.biglake_hive_v1.types.ListHiveTablesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.biglake_hive_v1.services.hive_metastore_service.pagers.ListHiveTablesAsyncPager", + "shortName": "list_hive_tables" + }, + "description": "Sample for ListHiveTables", + "file": "biglake_v1_generated_hive_metastore_service_list_hive_tables_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "biglake_v1_generated_HiveMetastoreService_ListHiveTables_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "biglake_v1_generated_hive_metastore_service_list_hive_tables_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.biglake_hive_v1.HiveMetastoreServiceClient", + "shortName": "HiveMetastoreServiceClient" + }, + "fullName": "google.cloud.biglake_hive_v1.HiveMetastoreServiceClient.list_hive_tables", + "method": { + "fullName": "google.cloud.biglake.hive.v1.HiveMetastoreService.ListHiveTables", + "service": { + "fullName": "google.cloud.biglake.hive.v1.HiveMetastoreService", + "shortName": "HiveMetastoreService" + }, + "shortName": "ListHiveTables" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.biglake_hive_v1.types.ListHiveTablesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.biglake_hive_v1.services.hive_metastore_service.pagers.ListHiveTablesPager", + "shortName": "list_hive_tables" + }, + "description": "Sample for ListHiveTables", + "file": "biglake_v1_generated_hive_metastore_service_list_hive_tables_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "biglake_v1_generated_HiveMetastoreService_ListHiveTables_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "biglake_v1_generated_hive_metastore_service_list_hive_tables_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.biglake_hive_v1.HiveMetastoreServiceAsyncClient", + "shortName": "HiveMetastoreServiceAsyncClient" + }, + "fullName": "google.cloud.biglake_hive_v1.HiveMetastoreServiceAsyncClient.list_partitions", + "method": { + "fullName": "google.cloud.biglake.hive.v1.HiveMetastoreService.ListPartitions", + "service": { + "fullName": "google.cloud.biglake.hive.v1.HiveMetastoreService", + "shortName": "HiveMetastoreService" + }, + "shortName": "ListPartitions" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.biglake_hive_v1.types.ListPartitionsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "Iterable[google.cloud.biglake_hive_v1.types.ListPartitionsResponse]", + "shortName": "list_partitions" + }, + "description": "Sample for ListPartitions", + "file": "biglake_v1_generated_hive_metastore_service_list_partitions_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "biglake_v1_generated_HiveMetastoreService_ListPartitions_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "biglake_v1_generated_hive_metastore_service_list_partitions_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.biglake_hive_v1.HiveMetastoreServiceClient", + "shortName": "HiveMetastoreServiceClient" + }, + "fullName": "google.cloud.biglake_hive_v1.HiveMetastoreServiceClient.list_partitions", + "method": { + "fullName": "google.cloud.biglake.hive.v1.HiveMetastoreService.ListPartitions", + "service": { + "fullName": "google.cloud.biglake.hive.v1.HiveMetastoreService", + "shortName": "HiveMetastoreService" + }, + "shortName": "ListPartitions" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.biglake_hive_v1.types.ListPartitionsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "Iterable[google.cloud.biglake_hive_v1.types.ListPartitionsResponse]", + "shortName": "list_partitions" + }, + "description": "Sample for ListPartitions", + "file": "biglake_v1_generated_hive_metastore_service_list_partitions_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "biglake_v1_generated_HiveMetastoreService_ListPartitions_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "biglake_v1_generated_hive_metastore_service_list_partitions_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.biglake_hive_v1.HiveMetastoreServiceAsyncClient", + "shortName": "HiveMetastoreServiceAsyncClient" + }, + "fullName": "google.cloud.biglake_hive_v1.HiveMetastoreServiceAsyncClient.update_hive_catalog", + "method": { + "fullName": "google.cloud.biglake.hive.v1.HiveMetastoreService.UpdateHiveCatalog", + "service": { + "fullName": "google.cloud.biglake.hive.v1.HiveMetastoreService", + "shortName": "HiveMetastoreService" + }, + "shortName": "UpdateHiveCatalog" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.biglake_hive_v1.types.UpdateHiveCatalogRequest" + }, + { + "name": "hive_catalog", + "type": "google.cloud.biglake_hive_v1.types.HiveCatalog" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.biglake_hive_v1.types.HiveCatalog", + "shortName": "update_hive_catalog" + }, + "description": "Sample for UpdateHiveCatalog", + "file": "biglake_v1_generated_hive_metastore_service_update_hive_catalog_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "biglake_v1_generated_HiveMetastoreService_UpdateHiveCatalog_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "biglake_v1_generated_hive_metastore_service_update_hive_catalog_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.biglake_hive_v1.HiveMetastoreServiceClient", + "shortName": "HiveMetastoreServiceClient" + }, + "fullName": "google.cloud.biglake_hive_v1.HiveMetastoreServiceClient.update_hive_catalog", + "method": { + "fullName": "google.cloud.biglake.hive.v1.HiveMetastoreService.UpdateHiveCatalog", + "service": { + "fullName": "google.cloud.biglake.hive.v1.HiveMetastoreService", + "shortName": "HiveMetastoreService" + }, + "shortName": "UpdateHiveCatalog" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.biglake_hive_v1.types.UpdateHiveCatalogRequest" + }, + { + "name": "hive_catalog", + "type": "google.cloud.biglake_hive_v1.types.HiveCatalog" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.biglake_hive_v1.types.HiveCatalog", + "shortName": "update_hive_catalog" + }, + "description": "Sample for UpdateHiveCatalog", + "file": "biglake_v1_generated_hive_metastore_service_update_hive_catalog_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "biglake_v1_generated_HiveMetastoreService_UpdateHiveCatalog_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "biglake_v1_generated_hive_metastore_service_update_hive_catalog_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.biglake_hive_v1.HiveMetastoreServiceAsyncClient", + "shortName": "HiveMetastoreServiceAsyncClient" + }, + "fullName": "google.cloud.biglake_hive_v1.HiveMetastoreServiceAsyncClient.update_hive_database", + "method": { + "fullName": "google.cloud.biglake.hive.v1.HiveMetastoreService.UpdateHiveDatabase", + "service": { + "fullName": "google.cloud.biglake.hive.v1.HiveMetastoreService", + "shortName": "HiveMetastoreService" + }, + "shortName": "UpdateHiveDatabase" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.biglake_hive_v1.types.UpdateHiveDatabaseRequest" + }, + { + "name": "hive_database", + "type": "google.cloud.biglake_hive_v1.types.HiveDatabase" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.biglake_hive_v1.types.HiveDatabase", + "shortName": "update_hive_database" + }, + "description": "Sample for UpdateHiveDatabase", + "file": "biglake_v1_generated_hive_metastore_service_update_hive_database_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "biglake_v1_generated_HiveMetastoreService_UpdateHiveDatabase_async", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "biglake_v1_generated_hive_metastore_service_update_hive_database_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.biglake_hive_v1.HiveMetastoreServiceClient", + "shortName": "HiveMetastoreServiceClient" + }, + "fullName": "google.cloud.biglake_hive_v1.HiveMetastoreServiceClient.update_hive_database", + "method": { + "fullName": "google.cloud.biglake.hive.v1.HiveMetastoreService.UpdateHiveDatabase", + "service": { + "fullName": "google.cloud.biglake.hive.v1.HiveMetastoreService", + "shortName": "HiveMetastoreService" + }, + "shortName": "UpdateHiveDatabase" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.biglake_hive_v1.types.UpdateHiveDatabaseRequest" + }, + { + "name": "hive_database", + "type": "google.cloud.biglake_hive_v1.types.HiveDatabase" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.biglake_hive_v1.types.HiveDatabase", + "shortName": "update_hive_database" + }, + "description": "Sample for UpdateHiveDatabase", + "file": "biglake_v1_generated_hive_metastore_service_update_hive_database_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "biglake_v1_generated_HiveMetastoreService_UpdateHiveDatabase_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "biglake_v1_generated_hive_metastore_service_update_hive_database_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.biglake_hive_v1.HiveMetastoreServiceAsyncClient", + "shortName": "HiveMetastoreServiceAsyncClient" + }, + "fullName": "google.cloud.biglake_hive_v1.HiveMetastoreServiceAsyncClient.update_hive_table", + "method": { + "fullName": "google.cloud.biglake.hive.v1.HiveMetastoreService.UpdateHiveTable", + "service": { + "fullName": "google.cloud.biglake.hive.v1.HiveMetastoreService", + "shortName": "HiveMetastoreService" + }, + "shortName": "UpdateHiveTable" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.biglake_hive_v1.types.UpdateHiveTableRequest" + }, + { + "name": "hive_table", + "type": "google.cloud.biglake_hive_v1.types.HiveTable" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.biglake_hive_v1.types.HiveTable", + "shortName": "update_hive_table" + }, + "description": "Sample for UpdateHiveTable", + "file": "biglake_v1_generated_hive_metastore_service_update_hive_table_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "biglake_v1_generated_HiveMetastoreService_UpdateHiveTable_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "biglake_v1_generated_hive_metastore_service_update_hive_table_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.biglake_hive_v1.HiveMetastoreServiceClient", + "shortName": "HiveMetastoreServiceClient" + }, + "fullName": "google.cloud.biglake_hive_v1.HiveMetastoreServiceClient.update_hive_table", + "method": { + "fullName": "google.cloud.biglake.hive.v1.HiveMetastoreService.UpdateHiveTable", + "service": { + "fullName": "google.cloud.biglake.hive.v1.HiveMetastoreService", + "shortName": "HiveMetastoreService" + }, + "shortName": "UpdateHiveTable" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.biglake_hive_v1.types.UpdateHiveTableRequest" + }, + { + "name": "hive_table", + "type": "google.cloud.biglake_hive_v1.types.HiveTable" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.biglake_hive_v1.types.HiveTable", + "shortName": "update_hive_table" + }, + "description": "Sample for UpdateHiveTable", + "file": "biglake_v1_generated_hive_metastore_service_update_hive_table_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "biglake_v1_generated_HiveMetastoreService_UpdateHiveTable_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "biglake_v1_generated_hive_metastore_service_update_hive_table_sync.py" + } + ] +} diff --git a/packages/google-cloud-biglake-hive/tests/unit/gapic/biglake_hive_v1/__init__.py b/packages/google-cloud-biglake-hive/tests/unit/gapic/biglake_hive_v1/__init__.py new file mode 100644 index 000000000000..32b36c5c4fe0 --- /dev/null +++ b/packages/google-cloud-biglake-hive/tests/unit/gapic/biglake_hive_v1/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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. +# diff --git a/packages/google-cloud-biglake-hive/tests/unit/gapic/biglake_hive_v1/test_hive_metastore_service.py b/packages/google-cloud-biglake-hive/tests/unit/gapic/biglake_hive_v1/test_hive_metastore_service.py new file mode 100644 index 000000000000..0d16c3cc15de --- /dev/null +++ b/packages/google-cloud-biglake-hive/tests/unit/gapic/biglake_hive_v1/test_hive_metastore_service.py @@ -0,0 +1,18487 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 asyncio +import json +import math +import os +from collections.abc import AsyncIterable, Iterable, Mapping, Sequence +from unittest import mock +from unittest.mock import AsyncMock + +import grpc +import pytest +from google.api_core import api_core_version +from google.protobuf import json_format +from grpc.experimental import aio +from proto.marshal.rules import wrappers +from proto.marshal.rules.dates import DurationRule, TimestampRule +from requests import PreparedRequest, Request, Response +from requests.sessions import Session + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + +import google.auth +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +from google.api_core import ( + client_options, + gapic_v1, + grpc_helpers, + grpc_helpers_async, + path_template, +) +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.oauth2 import service_account + +from google.cloud.biglake_hive_v1.services.hive_metastore_service import ( + HiveMetastoreServiceAsyncClient, + HiveMetastoreServiceClient, + pagers, + transports, +) +from google.cloud.biglake_hive_v1.types import hive_metastore + +CRED_INFO_JSON = { + "credential_source": "/path/to/file", + "credential_type": "service account credentials", + "principal": "service-account@example.com", +} +CRED_INFO_STRING = json.dumps(CRED_INFO_JSON) + + +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + + +# If default endpoint template is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint template so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint_template(client): + return ( + "test.{UNIVERSE_DOMAIN}" + if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) + else client._DEFAULT_ENDPOINT_TEMPLATE + ) + + +@pytest.fixture(autouse=True) +def set_event_loop(): + try: + asyncio.get_running_loop() + yield + except RuntimeError: + loop = asyncio.new_event_loop() + asyncio.set_event_loop(loop) + try: + yield + finally: + loop.close() + asyncio.set_event_loop(None) + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + custom_endpoint = ".custom" + + assert HiveMetastoreServiceClient._get_default_mtls_endpoint(None) is None + assert ( + HiveMetastoreServiceClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + HiveMetastoreServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + HiveMetastoreServiceClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + HiveMetastoreServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + HiveMetastoreServiceClient._get_default_mtls_endpoint(non_googleapi) + == non_googleapi + ) + assert ( + HiveMetastoreServiceClient._get_default_mtls_endpoint(custom_endpoint) + == custom_endpoint + ) + + +def test__read_environment_variables(): + assert HiveMetastoreServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert HiveMetastoreServiceClient._read_environment_variables() == ( + True, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert HiveMetastoreServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with pytest.raises(ValueError) as excinfo: + HiveMetastoreServiceClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + else: + assert HiveMetastoreServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert HiveMetastoreServiceClient._read_environment_variables() == ( + False, + "never", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert HiveMetastoreServiceClient._read_environment_variables() == ( + False, + "always", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert HiveMetastoreServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + HiveMetastoreServiceClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): + assert HiveMetastoreServiceClient._read_environment_variables() == ( + False, + "auto", + "foo.com", + ) + + +def test_use_client_cert_effective(): + # Test case 1: Test when `should_use_client_cert` returns True. + # We mock the `should_use_client_cert` function to simulate a scenario where + # the google-auth library supports automatic mTLS and determines that a + # client certificate should be used. + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch( + "google.auth.transport.mtls.should_use_client_cert", return_value=True + ): + assert HiveMetastoreServiceClient._use_client_cert_effective() is True + + # Test case 2: Test when `should_use_client_cert` returns False. + # We mock the `should_use_client_cert` function to simulate a scenario where + # the google-auth library supports automatic mTLS and determines that a + # client certificate should NOT be used. + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch( + "google.auth.transport.mtls.should_use_client_cert", return_value=False + ): + assert HiveMetastoreServiceClient._use_client_cert_effective() is False + + # Test case 3: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "true". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert HiveMetastoreServiceClient._use_client_cert_effective() is True + + # Test case 4: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "false". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"} + ): + assert HiveMetastoreServiceClient._use_client_cert_effective() is False + + # Test case 5: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "True". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "True"}): + assert HiveMetastoreServiceClient._use_client_cert_effective() is True + + # Test case 6: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "False". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "False"} + ): + assert HiveMetastoreServiceClient._use_client_cert_effective() is False + + # Test case 7: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "TRUE". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "TRUE"}): + assert HiveMetastoreServiceClient._use_client_cert_effective() is True + + # Test case 8: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "FALSE". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "FALSE"} + ): + assert HiveMetastoreServiceClient._use_client_cert_effective() is False + + # Test case 9: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not set. + # In this case, the method should return False, which is the default value. + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, clear=True): + assert HiveMetastoreServiceClient._use_client_cert_effective() is False + + # Test case 10: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to an invalid value. + # The method should raise a ValueError as the environment variable must be either + # "true" or "false". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"} + ): + with pytest.raises(ValueError): + HiveMetastoreServiceClient._use_client_cert_effective() + + # Test case 11: Test when `should_use_client_cert` is available and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to an invalid value. + # The method should return False as the environment variable is set to an invalid value. + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"} + ): + assert HiveMetastoreServiceClient._use_client_cert_effective() is False + + # Test case 12: Test when `should_use_client_cert` is available and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is unset. Also, + # the GOOGLE_API_CONFIG environment variable is unset. + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": ""}): + with mock.patch.dict(os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": ""}): + assert HiveMetastoreServiceClient._use_client_cert_effective() is False + + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert HiveMetastoreServiceClient._get_client_cert_source(None, False) is None + assert ( + HiveMetastoreServiceClient._get_client_cert_source( + mock_provided_cert_source, False + ) + is None + ) + assert ( + HiveMetastoreServiceClient._get_client_cert_source( + mock_provided_cert_source, True + ) + == mock_provided_cert_source + ) + + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", return_value=True + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_default_cert_source, + ): + assert ( + HiveMetastoreServiceClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + HiveMetastoreServiceClient._get_client_cert_source( + mock_provided_cert_source, "true" + ) + is mock_provided_cert_source + ) + + +@mock.patch.object( + HiveMetastoreServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(HiveMetastoreServiceClient), +) +@mock.patch.object( + HiveMetastoreServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(HiveMetastoreServiceAsyncClient), +) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = HiveMetastoreServiceClient._DEFAULT_UNIVERSE + default_endpoint = HiveMetastoreServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = HiveMetastoreServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + assert ( + HiveMetastoreServiceClient._get_api_endpoint( + api_override, mock_client_cert_source, default_universe, "always" + ) + == api_override + ) + assert ( + HiveMetastoreServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "auto" + ) + == HiveMetastoreServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + HiveMetastoreServiceClient._get_api_endpoint( + None, None, default_universe, "auto" + ) + == default_endpoint + ) + assert ( + HiveMetastoreServiceClient._get_api_endpoint( + None, None, default_universe, "always" + ) + == HiveMetastoreServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + HiveMetastoreServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "always" + ) + == HiveMetastoreServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + HiveMetastoreServiceClient._get_api_endpoint(None, None, mock_universe, "never") + == mock_endpoint + ) + assert ( + HiveMetastoreServiceClient._get_api_endpoint( + None, None, default_universe, "never" + ) + == default_endpoint + ) + + with pytest.raises(MutualTLSChannelError) as excinfo: + HiveMetastoreServiceClient._get_api_endpoint( + None, mock_client_cert_source, mock_universe, "auto" + ) + assert ( + str(excinfo.value) + == "mTLS is not supported in any universe other than googleapis.com." + ) + + +def test__get_universe_domain(): + client_universe_domain = "foo.com" + universe_domain_env = "bar.com" + + assert ( + HiveMetastoreServiceClient._get_universe_domain( + client_universe_domain, universe_domain_env + ) + == client_universe_domain + ) + assert ( + HiveMetastoreServiceClient._get_universe_domain(None, universe_domain_env) + == universe_domain_env + ) + assert ( + HiveMetastoreServiceClient._get_universe_domain(None, None) + == HiveMetastoreServiceClient._DEFAULT_UNIVERSE + ) + + with pytest.raises(ValueError) as excinfo: + HiveMetastoreServiceClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + + +@pytest.mark.parametrize( + "error_code,cred_info_json,show_cred_info", + [ + (401, CRED_INFO_JSON, True), + (403, CRED_INFO_JSON, True), + (404, CRED_INFO_JSON, True), + (500, CRED_INFO_JSON, False), + (401, None, False), + (403, None, False), + (404, None, False), + (500, None, False), + ], +) +def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_info): + cred = mock.Mock(["get_cred_info"]) + cred.get_cred_info = mock.Mock(return_value=cred_info_json) + client = HiveMetastoreServiceClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=["foo"]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + if show_cred_info: + assert error.details == ["foo", CRED_INFO_STRING] + else: + assert error.details == ["foo"] + + +@pytest.mark.parametrize("error_code", [401, 403, 404, 500]) +def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code): + cred = mock.Mock([]) + assert not hasattr(cred, "get_cred_info") + client = HiveMetastoreServiceClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=[]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + assert error.details == [] + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (HiveMetastoreServiceClient, "grpc"), + (HiveMetastoreServiceAsyncClient, "grpc_asyncio"), + (HiveMetastoreServiceClient, "rest"), + ], +) +def test_hive_metastore_service_client_from_service_account_info( + client_class, transport_name +): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_info" + ) as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + "biglake.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://biglake.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_class,transport_name", + [ + (transports.HiveMetastoreServiceGrpcTransport, "grpc"), + (transports.HiveMetastoreServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.HiveMetastoreServiceRestTransport, "rest"), + ], +) +def test_hive_metastore_service_client_service_account_always_use_jwt( + transport_class, transport_name +): + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (HiveMetastoreServiceClient, "grpc"), + (HiveMetastoreServiceAsyncClient, "grpc_asyncio"), + (HiveMetastoreServiceClient, "rest"), + ], +) +def test_hive_metastore_service_client_from_service_account_file( + client_class, transport_name +): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_file" + ) as factory: + factory.return_value = creds + client = client_class.from_service_account_file( + "dummy/file/path.json", transport=transport_name + ) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json( + "dummy/file/path.json", transport=transport_name + ) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + "biglake.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://biglake.googleapis.com" + ) + + +def test_hive_metastore_service_client_get_transport_class(): + transport = HiveMetastoreServiceClient.get_transport_class() + available_transports = [ + transports.HiveMetastoreServiceGrpcTransport, + transports.HiveMetastoreServiceRestTransport, + ] + assert transport in available_transports + + transport = HiveMetastoreServiceClient.get_transport_class("grpc") + assert transport == transports.HiveMetastoreServiceGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + HiveMetastoreServiceClient, + transports.HiveMetastoreServiceGrpcTransport, + "grpc", + ), + ( + HiveMetastoreServiceAsyncClient, + transports.HiveMetastoreServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ( + HiveMetastoreServiceClient, + transports.HiveMetastoreServiceRestTransport, + "rest", + ), + ], +) +@mock.patch.object( + HiveMetastoreServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(HiveMetastoreServiceClient), +) +@mock.patch.object( + HiveMetastoreServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(HiveMetastoreServiceAsyncClient), +) +def test_hive_metastore_service_client_client_options( + client_class, transport_class, transport_name +): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(HiveMetastoreServiceClient, "get_transport_class") as gtc: + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(HiveMetastoreServiceClient, "get_transport_class") as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client = client_class(transport=transport_name) + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions( + api_audience="https://language.googleapis.com" + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com", + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + ( + HiveMetastoreServiceClient, + transports.HiveMetastoreServiceGrpcTransport, + "grpc", + "true", + ), + ( + HiveMetastoreServiceAsyncClient, + transports.HiveMetastoreServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + ( + HiveMetastoreServiceClient, + transports.HiveMetastoreServiceGrpcTransport, + "grpc", + "false", + ), + ( + HiveMetastoreServiceAsyncClient, + transports.HiveMetastoreServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ( + HiveMetastoreServiceClient, + transports.HiveMetastoreServiceRestTransport, + "rest", + "true", + ), + ( + HiveMetastoreServiceClient, + transports.HiveMetastoreServiceRestTransport, + "rest", + "false", + ), + ], +) +@mock.patch.object( + HiveMetastoreServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(HiveMetastoreServiceClient), +) +@mock.patch.object( + HiveMetastoreServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(HiveMetastoreServiceAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_hive_metastore_service_client_mtls_env_auto( + client_class, transport_class, transport_name, use_client_cert_env +): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=client_cert_source_callback, + ): + if use_client_cert_env == "false": + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class", [HiveMetastoreServiceClient, HiveMetastoreServiceAsyncClient] +) +@mock.patch.object( + HiveMetastoreServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(HiveMetastoreServiceClient), +) +@mock.patch.object( + HiveMetastoreServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(HiveMetastoreServiceAsyncClient), +) +def test_hive_metastore_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "Unsupported". + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset. + test_cases = [ + ( + # With workloads present in config, mTLS is enabled. + { + "version": 1, + "cert_configs": { + "workload": { + "cert_path": "path/to/cert/file", + "key_path": "path/to/key/file", + } + }, + }, + mock_client_cert_source, + ), + ( + # With workloads not present in config, mTLS is disabled. + { + "version": 1, + "cert_configs": {}, + }, + None, + ), + ] + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + for config_data, expected_cert_source in test_cases: + env = os.environ.copy() + env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", None) + with mock.patch.dict(os.environ, env, clear=True): + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with ( + mock.patch("builtins.open", m), + mock.patch( + "os.path.exists", + side_effect=lambda path: os.path.basename(path) + == config_filename, + ), + ): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source(options) + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is expected_cert_source + + # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset(empty). + test_cases = [ + ( + # With workloads present in config, mTLS is enabled. + { + "version": 1, + "cert_configs": { + "workload": { + "cert_path": "path/to/cert/file", + "key_path": "path/to/key/file", + } + }, + }, + mock_client_cert_source, + ), + ( + # With workloads not present in config, mTLS is disabled. + { + "version": 1, + "cert_configs": {}, + }, + None, + ), + ] + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + for config_data, expected_cert_source in test_cases: + env = os.environ.copy() + env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", "") + with mock.patch.dict(os.environ, env, clear=True): + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with ( + mock.patch("builtins.open", m), + mock.patch( + "os.path.exists", + side_effect=lambda path: os.path.basename(path) + == config_filename, + ), + ): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source(options) + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is expected_cert_source + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_client_cert_source, + ): + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source() + ) + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + +@pytest.mark.parametrize( + "client_class", [HiveMetastoreServiceClient, HiveMetastoreServiceAsyncClient] +) +@mock.patch.object( + HiveMetastoreServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(HiveMetastoreServiceClient), +) +@mock.patch.object( + HiveMetastoreServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(HiveMetastoreServiceAsyncClient), +) +def test_hive_metastore_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = HiveMetastoreServiceClient._DEFAULT_UNIVERSE + default_endpoint = HiveMetastoreServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = HiveMetastoreServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", + # use ClientOptions.api_endpoint as the api endpoint regardless. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ): + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=api_override + ) + client = client_class( + client_options=options, + credentials=ga_credentials.AnonymousCredentials(), + ) + assert client.api_endpoint == api_override + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", + # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + + # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), + # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, + # and ClientOptions.universe_domain="bar.com", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. + options = client_options.ClientOptions() + universe_exists = hasattr(options, "universe_domain") + if universe_exists: + options = client_options.ClientOptions(universe_domain=mock_universe) + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + else: + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == ( + mock_endpoint if universe_exists else default_endpoint + ) + assert client.universe_domain == ( + mock_universe if universe_exists else default_universe + ) + + # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + options = client_options.ClientOptions() + if hasattr(options, "universe_domain"): + delattr(options, "universe_domain") + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == default_endpoint + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + HiveMetastoreServiceClient, + transports.HiveMetastoreServiceGrpcTransport, + "grpc", + ), + ( + HiveMetastoreServiceAsyncClient, + transports.HiveMetastoreServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ( + HiveMetastoreServiceClient, + transports.HiveMetastoreServiceRestTransport, + "rest", + ), + ], +) +def test_hive_metastore_service_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + ( + HiveMetastoreServiceClient, + transports.HiveMetastoreServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + HiveMetastoreServiceAsyncClient, + transports.HiveMetastoreServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ( + HiveMetastoreServiceClient, + transports.HiveMetastoreServiceRestTransport, + "rest", + None, + ), + ], +) +def test_hive_metastore_service_client_client_options_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +def test_hive_metastore_service_client_client_options_from_dict(): + with mock.patch( + "google.cloud.biglake_hive_v1.services.hive_metastore_service.transports.HiveMetastoreServiceGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = HiveMetastoreServiceClient( + client_options={"api_endpoint": "squid.clam.whelk"} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + ( + HiveMetastoreServiceClient, + transports.HiveMetastoreServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + HiveMetastoreServiceAsyncClient, + transports.HiveMetastoreServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_hive_metastore_service_client_create_channel_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with ( + mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, + mock.patch.object(google.auth, "default", autospec=True) as adc, + mock.patch.object(grpc_helpers, "create_channel") as create_channel, + ): + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "biglake.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( + "https://www.googleapis.com/auth/bigquery", + "https://www.googleapis.com/auth/cloud-platform", + ), + scopes=None, + default_host="biglake.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "request_type", + [ + hive_metastore.CreateHiveCatalogRequest(), + {}, + ], +) +def test_create_hive_catalog(request_type, transport: str = "grpc"): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_hive_catalog), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = hive_metastore.HiveCatalog( + name="name_value", + description="description_value", + location_uri="location_uri_value", + ) + response = client.create_hive_catalog(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = hive_metastore.CreateHiveCatalogRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, hive_metastore.HiveCatalog) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.location_uri == "location_uri_value" + + +def test_create_hive_catalog_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = hive_metastore.CreateHiveCatalogRequest( + parent="parent_value", + hive_catalog_id="hive_catalog_id_value", + primary_location="primary_location_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_hive_catalog), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_hive_catalog(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hive_metastore.CreateHiveCatalogRequest( + parent="parent_value", + hive_catalog_id="hive_catalog_id_value", + primary_location="primary_location_value", + ) + assert args[0] == request_msg + + +def test_create_hive_catalog_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_hive_catalog in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.create_hive_catalog] = ( + mock_rpc + ) + request = {} + client.create_hive_catalog(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_hive_catalog(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_hive_catalog_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.create_hive_catalog + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.create_hive_catalog + ] = mock_rpc + + request = {} + await client.create_hive_catalog(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.create_hive_catalog(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + hive_metastore.CreateHiveCatalogRequest(), + {}, + ], +) +async def test_create_hive_catalog_async(request_type, transport: str = "grpc_asyncio"): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_hive_catalog), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hive_metastore.HiveCatalog( + name="name_value", + description="description_value", + location_uri="location_uri_value", + ) + ) + response = await client.create_hive_catalog(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = hive_metastore.CreateHiveCatalogRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, hive_metastore.HiveCatalog) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.location_uri == "location_uri_value" + + +def test_create_hive_catalog_field_headers(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = hive_metastore.CreateHiveCatalogRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_hive_catalog), "__call__" + ) as call: + call.return_value = hive_metastore.HiveCatalog() + client.create_hive_catalog(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_create_hive_catalog_field_headers_async(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = hive_metastore.CreateHiveCatalogRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_hive_catalog), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hive_metastore.HiveCatalog() + ) + await client.create_hive_catalog(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_create_hive_catalog_flattened(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_hive_catalog), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = hive_metastore.HiveCatalog() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_hive_catalog( + parent="parent_value", + hive_catalog=hive_metastore.HiveCatalog(name="name_value"), + hive_catalog_id="hive_catalog_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].hive_catalog + mock_val = hive_metastore.HiveCatalog(name="name_value") + assert arg == mock_val + arg = args[0].hive_catalog_id + mock_val = "hive_catalog_id_value" + assert arg == mock_val + + +def test_create_hive_catalog_flattened_error(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_hive_catalog( + hive_metastore.CreateHiveCatalogRequest(), + parent="parent_value", + hive_catalog=hive_metastore.HiveCatalog(name="name_value"), + hive_catalog_id="hive_catalog_id_value", + ) + + +@pytest.mark.asyncio +async def test_create_hive_catalog_flattened_async(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_hive_catalog), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = hive_metastore.HiveCatalog() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hive_metastore.HiveCatalog() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_hive_catalog( + parent="parent_value", + hive_catalog=hive_metastore.HiveCatalog(name="name_value"), + hive_catalog_id="hive_catalog_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].hive_catalog + mock_val = hive_metastore.HiveCatalog(name="name_value") + assert arg == mock_val + arg = args[0].hive_catalog_id + mock_val = "hive_catalog_id_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_hive_catalog_flattened_error_async(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_hive_catalog( + hive_metastore.CreateHiveCatalogRequest(), + parent="parent_value", + hive_catalog=hive_metastore.HiveCatalog(name="name_value"), + hive_catalog_id="hive_catalog_id_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + hive_metastore.GetHiveCatalogRequest(), + {}, + ], +) +def test_get_hive_catalog(request_type, transport: str = "grpc"): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_hive_catalog), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = hive_metastore.HiveCatalog( + name="name_value", + description="description_value", + location_uri="location_uri_value", + ) + response = client.get_hive_catalog(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = hive_metastore.GetHiveCatalogRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, hive_metastore.HiveCatalog) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.location_uri == "location_uri_value" + + +def test_get_hive_catalog_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = hive_metastore.GetHiveCatalogRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_hive_catalog), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_hive_catalog(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hive_metastore.GetHiveCatalogRequest( + name="name_value", + ) + assert args[0] == request_msg + + +def test_get_hive_catalog_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_hive_catalog in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_hive_catalog] = ( + mock_rpc + ) + request = {} + client.get_hive_catalog(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_hive_catalog(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_hive_catalog_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.get_hive_catalog + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.get_hive_catalog + ] = mock_rpc + + request = {} + await client.get_hive_catalog(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_hive_catalog(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + hive_metastore.GetHiveCatalogRequest(), + {}, + ], +) +async def test_get_hive_catalog_async(request_type, transport: str = "grpc_asyncio"): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_hive_catalog), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hive_metastore.HiveCatalog( + name="name_value", + description="description_value", + location_uri="location_uri_value", + ) + ) + response = await client.get_hive_catalog(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = hive_metastore.GetHiveCatalogRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, hive_metastore.HiveCatalog) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.location_uri == "location_uri_value" + + +def test_get_hive_catalog_field_headers(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = hive_metastore.GetHiveCatalogRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_hive_catalog), "__call__") as call: + call.return_value = hive_metastore.HiveCatalog() + client.get_hive_catalog(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_hive_catalog_field_headers_async(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = hive_metastore.GetHiveCatalogRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_hive_catalog), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hive_metastore.HiveCatalog() + ) + await client.get_hive_catalog(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_get_hive_catalog_flattened(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_hive_catalog), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = hive_metastore.HiveCatalog() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_hive_catalog( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_get_hive_catalog_flattened_error(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_hive_catalog( + hive_metastore.GetHiveCatalogRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_hive_catalog_flattened_async(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_hive_catalog), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = hive_metastore.HiveCatalog() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hive_metastore.HiveCatalog() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_hive_catalog( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_hive_catalog_flattened_error_async(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_hive_catalog( + hive_metastore.GetHiveCatalogRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + hive_metastore.ListHiveCatalogsRequest(), + {}, + ], +) +def test_list_hive_catalogs(request_type, transport: str = "grpc"): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_hive_catalogs), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = hive_metastore.ListHiveCatalogsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + response = client.list_hive_catalogs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = hive_metastore.ListHiveCatalogsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListHiveCatalogsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_hive_catalogs_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = hive_metastore.ListHiveCatalogsRequest( + parent="parent_value", + page_token="page_token_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_hive_catalogs), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_hive_catalogs(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hive_metastore.ListHiveCatalogsRequest( + parent="parent_value", + page_token="page_token_value", + ) + assert args[0] == request_msg + + +def test_list_hive_catalogs_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_hive_catalogs in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list_hive_catalogs] = ( + mock_rpc + ) + request = {} + client.list_hive_catalogs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_hive_catalogs(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_hive_catalogs_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.list_hive_catalogs + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_hive_catalogs + ] = mock_rpc + + request = {} + await client.list_hive_catalogs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_hive_catalogs(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + hive_metastore.ListHiveCatalogsRequest(), + {}, + ], +) +async def test_list_hive_catalogs_async(request_type, transport: str = "grpc_asyncio"): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_hive_catalogs), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hive_metastore.ListHiveCatalogsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + response = await client.list_hive_catalogs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = hive_metastore.ListHiveCatalogsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListHiveCatalogsAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_hive_catalogs_field_headers(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = hive_metastore.ListHiveCatalogsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_hive_catalogs), "__call__" + ) as call: + call.return_value = hive_metastore.ListHiveCatalogsResponse() + client.list_hive_catalogs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_hive_catalogs_field_headers_async(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = hive_metastore.ListHiveCatalogsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_hive_catalogs), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hive_metastore.ListHiveCatalogsResponse() + ) + await client.list_hive_catalogs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_list_hive_catalogs_flattened(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_hive_catalogs), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = hive_metastore.ListHiveCatalogsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_hive_catalogs( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +def test_list_hive_catalogs_flattened_error(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_hive_catalogs( + hive_metastore.ListHiveCatalogsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_hive_catalogs_flattened_async(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_hive_catalogs), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = hive_metastore.ListHiveCatalogsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hive_metastore.ListHiveCatalogsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_hive_catalogs( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_hive_catalogs_flattened_error_async(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_hive_catalogs( + hive_metastore.ListHiveCatalogsRequest(), + parent="parent_value", + ) + + +def test_list_hive_catalogs_pager(transport_name: str = "grpc"): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_hive_catalogs), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + hive_metastore.ListHiveCatalogsResponse( + catalogs=[ + hive_metastore.HiveCatalog(), + hive_metastore.HiveCatalog(), + hive_metastore.HiveCatalog(), + ], + next_page_token="abc", + ), + hive_metastore.ListHiveCatalogsResponse( + catalogs=[], + next_page_token="def", + ), + hive_metastore.ListHiveCatalogsResponse( + catalogs=[ + hive_metastore.HiveCatalog(), + ], + next_page_token="ghi", + ), + hive_metastore.ListHiveCatalogsResponse( + catalogs=[ + hive_metastore.HiveCatalog(), + hive_metastore.HiveCatalog(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_hive_catalogs(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, hive_metastore.HiveCatalog) for i in results) + + +def test_list_hive_catalogs_pages(transport_name: str = "grpc"): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_hive_catalogs), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + hive_metastore.ListHiveCatalogsResponse( + catalogs=[ + hive_metastore.HiveCatalog(), + hive_metastore.HiveCatalog(), + hive_metastore.HiveCatalog(), + ], + next_page_token="abc", + ), + hive_metastore.ListHiveCatalogsResponse( + catalogs=[], + next_page_token="def", + ), + hive_metastore.ListHiveCatalogsResponse( + catalogs=[ + hive_metastore.HiveCatalog(), + ], + next_page_token="ghi", + ), + hive_metastore.ListHiveCatalogsResponse( + catalogs=[ + hive_metastore.HiveCatalog(), + hive_metastore.HiveCatalog(), + ], + ), + RuntimeError, + ) + pages = list(client.list_hive_catalogs(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_hive_catalogs_async_pager(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_hive_catalogs), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + hive_metastore.ListHiveCatalogsResponse( + catalogs=[ + hive_metastore.HiveCatalog(), + hive_metastore.HiveCatalog(), + hive_metastore.HiveCatalog(), + ], + next_page_token="abc", + ), + hive_metastore.ListHiveCatalogsResponse( + catalogs=[], + next_page_token="def", + ), + hive_metastore.ListHiveCatalogsResponse( + catalogs=[ + hive_metastore.HiveCatalog(), + ], + next_page_token="ghi", + ), + hive_metastore.ListHiveCatalogsResponse( + catalogs=[ + hive_metastore.HiveCatalog(), + hive_metastore.HiveCatalog(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_hive_catalogs( + request={}, + ) + assert async_pager.next_page_token == "abc" + assert str(async_pager).startswith(f"{async_pager.__class__.__name__}<") + + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, hive_metastore.HiveCatalog) for i in responses) + + +@pytest.mark.asyncio +async def test_list_hive_catalogs_async_pages(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_hive_catalogs), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + hive_metastore.ListHiveCatalogsResponse( + catalogs=[ + hive_metastore.HiveCatalog(), + hive_metastore.HiveCatalog(), + hive_metastore.HiveCatalog(), + ], + next_page_token="abc", + ), + hive_metastore.ListHiveCatalogsResponse( + catalogs=[], + next_page_token="def", + ), + hive_metastore.ListHiveCatalogsResponse( + catalogs=[ + hive_metastore.HiveCatalog(), + ], + next_page_token="ghi", + ), + hive_metastore.ListHiveCatalogsResponse( + catalogs=[ + hive_metastore.HiveCatalog(), + hive_metastore.HiveCatalog(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_hive_catalogs(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + hive_metastore.UpdateHiveCatalogRequest(), + {}, + ], +) +def test_update_hive_catalog(request_type, transport: str = "grpc"): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_hive_catalog), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = hive_metastore.HiveCatalog( + name="name_value", + description="description_value", + location_uri="location_uri_value", + ) + response = client.update_hive_catalog(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = hive_metastore.UpdateHiveCatalogRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, hive_metastore.HiveCatalog) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.location_uri == "location_uri_value" + + +def test_update_hive_catalog_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = hive_metastore.UpdateHiveCatalogRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_hive_catalog), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.update_hive_catalog(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hive_metastore.UpdateHiveCatalogRequest() + assert args[0] == request_msg + + +def test_update_hive_catalog_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.update_hive_catalog in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_hive_catalog] = ( + mock_rpc + ) + request = {} + client.update_hive_catalog(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_hive_catalog(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_hive_catalog_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.update_hive_catalog + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.update_hive_catalog + ] = mock_rpc + + request = {} + await client.update_hive_catalog(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_hive_catalog(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + hive_metastore.UpdateHiveCatalogRequest(), + {}, + ], +) +async def test_update_hive_catalog_async(request_type, transport: str = "grpc_asyncio"): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_hive_catalog), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hive_metastore.HiveCatalog( + name="name_value", + description="description_value", + location_uri="location_uri_value", + ) + ) + response = await client.update_hive_catalog(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = hive_metastore.UpdateHiveCatalogRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, hive_metastore.HiveCatalog) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.location_uri == "location_uri_value" + + +def test_update_hive_catalog_field_headers(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = hive_metastore.UpdateHiveCatalogRequest() + + request.hive_catalog.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_hive_catalog), "__call__" + ) as call: + call.return_value = hive_metastore.HiveCatalog() + client.update_hive_catalog(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "hive_catalog.name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_hive_catalog_field_headers_async(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = hive_metastore.UpdateHiveCatalogRequest() + + request.hive_catalog.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_hive_catalog), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hive_metastore.HiveCatalog() + ) + await client.update_hive_catalog(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "hive_catalog.name=name_value", + ) in kw["metadata"] + + +def test_update_hive_catalog_flattened(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_hive_catalog), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = hive_metastore.HiveCatalog() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_hive_catalog( + hive_catalog=hive_metastore.HiveCatalog(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].hive_catalog + mock_val = hive_metastore.HiveCatalog(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +def test_update_hive_catalog_flattened_error(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_hive_catalog( + hive_metastore.UpdateHiveCatalogRequest(), + hive_catalog=hive_metastore.HiveCatalog(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_hive_catalog_flattened_async(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_hive_catalog), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = hive_metastore.HiveCatalog() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hive_metastore.HiveCatalog() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_hive_catalog( + hive_catalog=hive_metastore.HiveCatalog(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].hive_catalog + mock_val = hive_metastore.HiveCatalog(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_update_hive_catalog_flattened_error_async(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_hive_catalog( + hive_metastore.UpdateHiveCatalogRequest(), + hive_catalog=hive_metastore.HiveCatalog(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + hive_metastore.DeleteHiveCatalogRequest(), + {}, + ], +) +def test_delete_hive_catalog(request_type, transport: str = "grpc"): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_hive_catalog), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_hive_catalog(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = hive_metastore.DeleteHiveCatalogRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_hive_catalog_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = hive_metastore.DeleteHiveCatalogRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_hive_catalog), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_hive_catalog(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hive_metastore.DeleteHiveCatalogRequest( + name="name_value", + ) + assert args[0] == request_msg + + +def test_delete_hive_catalog_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.delete_hive_catalog in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.delete_hive_catalog] = ( + mock_rpc + ) + request = {} + client.delete_hive_catalog(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_hive_catalog(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_hive_catalog_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.delete_hive_catalog + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.delete_hive_catalog + ] = mock_rpc + + request = {} + await client.delete_hive_catalog(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.delete_hive_catalog(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + hive_metastore.DeleteHiveCatalogRequest(), + {}, + ], +) +async def test_delete_hive_catalog_async(request_type, transport: str = "grpc_asyncio"): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_hive_catalog), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_hive_catalog(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = hive_metastore.DeleteHiveCatalogRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_hive_catalog_field_headers(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = hive_metastore.DeleteHiveCatalogRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_hive_catalog), "__call__" + ) as call: + call.return_value = None + client.delete_hive_catalog(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_hive_catalog_field_headers_async(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = hive_metastore.DeleteHiveCatalogRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_hive_catalog), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_hive_catalog(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_delete_hive_catalog_flattened(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_hive_catalog), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_hive_catalog( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_delete_hive_catalog_flattened_error(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_hive_catalog( + hive_metastore.DeleteHiveCatalogRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_hive_catalog_flattened_async(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_hive_catalog), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_hive_catalog( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_delete_hive_catalog_flattened_error_async(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_hive_catalog( + hive_metastore.DeleteHiveCatalogRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + hive_metastore.CreateHiveDatabaseRequest(), + {}, + ], +) +def test_create_hive_database(request_type, transport: str = "grpc"): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_hive_database), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = hive_metastore.HiveDatabase( + name="name_value", + description="description_value", + location_uri="location_uri_value", + ) + response = client.create_hive_database(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = hive_metastore.CreateHiveDatabaseRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, hive_metastore.HiveDatabase) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.location_uri == "location_uri_value" + + +def test_create_hive_database_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = hive_metastore.CreateHiveDatabaseRequest( + parent="parent_value", + hive_database_id="hive_database_id_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_hive_database), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_hive_database(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hive_metastore.CreateHiveDatabaseRequest( + parent="parent_value", + hive_database_id="hive_database_id_value", + ) + assert args[0] == request_msg + + +def test_create_hive_database_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_hive_database in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.create_hive_database] = ( + mock_rpc + ) + request = {} + client.create_hive_database(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_hive_database(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_hive_database_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.create_hive_database + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.create_hive_database + ] = mock_rpc + + request = {} + await client.create_hive_database(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.create_hive_database(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + hive_metastore.CreateHiveDatabaseRequest(), + {}, + ], +) +async def test_create_hive_database_async( + request_type, transport: str = "grpc_asyncio" +): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_hive_database), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hive_metastore.HiveDatabase( + name="name_value", + description="description_value", + location_uri="location_uri_value", + ) + ) + response = await client.create_hive_database(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = hive_metastore.CreateHiveDatabaseRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, hive_metastore.HiveDatabase) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.location_uri == "location_uri_value" + + +def test_create_hive_database_field_headers(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = hive_metastore.CreateHiveDatabaseRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_hive_database), "__call__" + ) as call: + call.return_value = hive_metastore.HiveDatabase() + client.create_hive_database(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_create_hive_database_field_headers_async(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = hive_metastore.CreateHiveDatabaseRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_hive_database), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hive_metastore.HiveDatabase() + ) + await client.create_hive_database(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_create_hive_database_flattened(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_hive_database), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = hive_metastore.HiveDatabase() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_hive_database( + parent="parent_value", + hive_database=hive_metastore.HiveDatabase(name="name_value"), + hive_database_id="hive_database_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].hive_database + mock_val = hive_metastore.HiveDatabase(name="name_value") + assert arg == mock_val + arg = args[0].hive_database_id + mock_val = "hive_database_id_value" + assert arg == mock_val + + +def test_create_hive_database_flattened_error(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_hive_database( + hive_metastore.CreateHiveDatabaseRequest(), + parent="parent_value", + hive_database=hive_metastore.HiveDatabase(name="name_value"), + hive_database_id="hive_database_id_value", + ) + + +@pytest.mark.asyncio +async def test_create_hive_database_flattened_async(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_hive_database), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = hive_metastore.HiveDatabase() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hive_metastore.HiveDatabase() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_hive_database( + parent="parent_value", + hive_database=hive_metastore.HiveDatabase(name="name_value"), + hive_database_id="hive_database_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].hive_database + mock_val = hive_metastore.HiveDatabase(name="name_value") + assert arg == mock_val + arg = args[0].hive_database_id + mock_val = "hive_database_id_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_hive_database_flattened_error_async(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_hive_database( + hive_metastore.CreateHiveDatabaseRequest(), + parent="parent_value", + hive_database=hive_metastore.HiveDatabase(name="name_value"), + hive_database_id="hive_database_id_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + hive_metastore.GetHiveDatabaseRequest(), + {}, + ], +) +def test_get_hive_database(request_type, transport: str = "grpc"): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_hive_database), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = hive_metastore.HiveDatabase( + name="name_value", + description="description_value", + location_uri="location_uri_value", + ) + response = client.get_hive_database(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = hive_metastore.GetHiveDatabaseRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, hive_metastore.HiveDatabase) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.location_uri == "location_uri_value" + + +def test_get_hive_database_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = hive_metastore.GetHiveDatabaseRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_hive_database), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_hive_database(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hive_metastore.GetHiveDatabaseRequest( + name="name_value", + ) + assert args[0] == request_msg + + +def test_get_hive_database_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_hive_database in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_hive_database] = ( + mock_rpc + ) + request = {} + client.get_hive_database(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_hive_database(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_hive_database_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.get_hive_database + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.get_hive_database + ] = mock_rpc + + request = {} + await client.get_hive_database(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_hive_database(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + hive_metastore.GetHiveDatabaseRequest(), + {}, + ], +) +async def test_get_hive_database_async(request_type, transport: str = "grpc_asyncio"): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_hive_database), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hive_metastore.HiveDatabase( + name="name_value", + description="description_value", + location_uri="location_uri_value", + ) + ) + response = await client.get_hive_database(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = hive_metastore.GetHiveDatabaseRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, hive_metastore.HiveDatabase) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.location_uri == "location_uri_value" + + +def test_get_hive_database_field_headers(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = hive_metastore.GetHiveDatabaseRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_hive_database), "__call__" + ) as call: + call.return_value = hive_metastore.HiveDatabase() + client.get_hive_database(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_hive_database_field_headers_async(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = hive_metastore.GetHiveDatabaseRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_hive_database), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hive_metastore.HiveDatabase() + ) + await client.get_hive_database(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_get_hive_database_flattened(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_hive_database), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = hive_metastore.HiveDatabase() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_hive_database( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_get_hive_database_flattened_error(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_hive_database( + hive_metastore.GetHiveDatabaseRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_hive_database_flattened_async(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_hive_database), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = hive_metastore.HiveDatabase() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hive_metastore.HiveDatabase() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_hive_database( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_hive_database_flattened_error_async(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_hive_database( + hive_metastore.GetHiveDatabaseRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + hive_metastore.ListHiveDatabasesRequest(), + {}, + ], +) +def test_list_hive_databases(request_type, transport: str = "grpc"): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_hive_databases), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = hive_metastore.ListHiveDatabasesResponse( + next_page_token="next_page_token_value", + ) + response = client.list_hive_databases(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = hive_metastore.ListHiveDatabasesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListHiveDatabasesPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_hive_databases_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = hive_metastore.ListHiveDatabasesRequest( + parent="parent_value", + page_token="page_token_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_hive_databases), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_hive_databases(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hive_metastore.ListHiveDatabasesRequest( + parent="parent_value", + page_token="page_token_value", + ) + assert args[0] == request_msg + + +def test_list_hive_databases_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_hive_databases in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list_hive_databases] = ( + mock_rpc + ) + request = {} + client.list_hive_databases(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_hive_databases(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_hive_databases_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.list_hive_databases + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_hive_databases + ] = mock_rpc + + request = {} + await client.list_hive_databases(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_hive_databases(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + hive_metastore.ListHiveDatabasesRequest(), + {}, + ], +) +async def test_list_hive_databases_async(request_type, transport: str = "grpc_asyncio"): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_hive_databases), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hive_metastore.ListHiveDatabasesResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_hive_databases(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = hive_metastore.ListHiveDatabasesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListHiveDatabasesAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_hive_databases_field_headers(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = hive_metastore.ListHiveDatabasesRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_hive_databases), "__call__" + ) as call: + call.return_value = hive_metastore.ListHiveDatabasesResponse() + client.list_hive_databases(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_hive_databases_field_headers_async(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = hive_metastore.ListHiveDatabasesRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_hive_databases), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hive_metastore.ListHiveDatabasesResponse() + ) + await client.list_hive_databases(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_list_hive_databases_flattened(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_hive_databases), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = hive_metastore.ListHiveDatabasesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_hive_databases( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +def test_list_hive_databases_flattened_error(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_hive_databases( + hive_metastore.ListHiveDatabasesRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_hive_databases_flattened_async(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_hive_databases), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = hive_metastore.ListHiveDatabasesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hive_metastore.ListHiveDatabasesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_hive_databases( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_hive_databases_flattened_error_async(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_hive_databases( + hive_metastore.ListHiveDatabasesRequest(), + parent="parent_value", + ) + + +def test_list_hive_databases_pager(transport_name: str = "grpc"): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_hive_databases), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + hive_metastore.ListHiveDatabasesResponse( + databases=[ + hive_metastore.HiveDatabase(), + hive_metastore.HiveDatabase(), + hive_metastore.HiveDatabase(), + ], + next_page_token="abc", + ), + hive_metastore.ListHiveDatabasesResponse( + databases=[], + next_page_token="def", + ), + hive_metastore.ListHiveDatabasesResponse( + databases=[ + hive_metastore.HiveDatabase(), + ], + next_page_token="ghi", + ), + hive_metastore.ListHiveDatabasesResponse( + databases=[ + hive_metastore.HiveDatabase(), + hive_metastore.HiveDatabase(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_hive_databases(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, hive_metastore.HiveDatabase) for i in results) + + +def test_list_hive_databases_pages(transport_name: str = "grpc"): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_hive_databases), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + hive_metastore.ListHiveDatabasesResponse( + databases=[ + hive_metastore.HiveDatabase(), + hive_metastore.HiveDatabase(), + hive_metastore.HiveDatabase(), + ], + next_page_token="abc", + ), + hive_metastore.ListHiveDatabasesResponse( + databases=[], + next_page_token="def", + ), + hive_metastore.ListHiveDatabasesResponse( + databases=[ + hive_metastore.HiveDatabase(), + ], + next_page_token="ghi", + ), + hive_metastore.ListHiveDatabasesResponse( + databases=[ + hive_metastore.HiveDatabase(), + hive_metastore.HiveDatabase(), + ], + ), + RuntimeError, + ) + pages = list(client.list_hive_databases(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_hive_databases_async_pager(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_hive_databases), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + hive_metastore.ListHiveDatabasesResponse( + databases=[ + hive_metastore.HiveDatabase(), + hive_metastore.HiveDatabase(), + hive_metastore.HiveDatabase(), + ], + next_page_token="abc", + ), + hive_metastore.ListHiveDatabasesResponse( + databases=[], + next_page_token="def", + ), + hive_metastore.ListHiveDatabasesResponse( + databases=[ + hive_metastore.HiveDatabase(), + ], + next_page_token="ghi", + ), + hive_metastore.ListHiveDatabasesResponse( + databases=[ + hive_metastore.HiveDatabase(), + hive_metastore.HiveDatabase(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_hive_databases( + request={}, + ) + assert async_pager.next_page_token == "abc" + assert str(async_pager).startswith(f"{async_pager.__class__.__name__}<") + + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, hive_metastore.HiveDatabase) for i in responses) + + +@pytest.mark.asyncio +async def test_list_hive_databases_async_pages(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_hive_databases), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + hive_metastore.ListHiveDatabasesResponse( + databases=[ + hive_metastore.HiveDatabase(), + hive_metastore.HiveDatabase(), + hive_metastore.HiveDatabase(), + ], + next_page_token="abc", + ), + hive_metastore.ListHiveDatabasesResponse( + databases=[], + next_page_token="def", + ), + hive_metastore.ListHiveDatabasesResponse( + databases=[ + hive_metastore.HiveDatabase(), + ], + next_page_token="ghi", + ), + hive_metastore.ListHiveDatabasesResponse( + databases=[ + hive_metastore.HiveDatabase(), + hive_metastore.HiveDatabase(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_hive_databases(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + hive_metastore.UpdateHiveDatabaseRequest(), + {}, + ], +) +def test_update_hive_database(request_type, transport: str = "grpc"): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_hive_database), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = hive_metastore.HiveDatabase( + name="name_value", + description="description_value", + location_uri="location_uri_value", + ) + response = client.update_hive_database(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = hive_metastore.UpdateHiveDatabaseRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, hive_metastore.HiveDatabase) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.location_uri == "location_uri_value" + + +def test_update_hive_database_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = hive_metastore.UpdateHiveDatabaseRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_hive_database), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.update_hive_database(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hive_metastore.UpdateHiveDatabaseRequest() + assert args[0] == request_msg + + +def test_update_hive_database_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.update_hive_database in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_hive_database] = ( + mock_rpc + ) + request = {} + client.update_hive_database(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_hive_database(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_hive_database_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.update_hive_database + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.update_hive_database + ] = mock_rpc + + request = {} + await client.update_hive_database(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_hive_database(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + hive_metastore.UpdateHiveDatabaseRequest(), + {}, + ], +) +async def test_update_hive_database_async( + request_type, transport: str = "grpc_asyncio" +): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_hive_database), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hive_metastore.HiveDatabase( + name="name_value", + description="description_value", + location_uri="location_uri_value", + ) + ) + response = await client.update_hive_database(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = hive_metastore.UpdateHiveDatabaseRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, hive_metastore.HiveDatabase) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.location_uri == "location_uri_value" + + +def test_update_hive_database_field_headers(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = hive_metastore.UpdateHiveDatabaseRequest() + + request.hive_database.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_hive_database), "__call__" + ) as call: + call.return_value = hive_metastore.HiveDatabase() + client.update_hive_database(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "hive_database.name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_hive_database_field_headers_async(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = hive_metastore.UpdateHiveDatabaseRequest() + + request.hive_database.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_hive_database), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hive_metastore.HiveDatabase() + ) + await client.update_hive_database(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "hive_database.name=name_value", + ) in kw["metadata"] + + +def test_update_hive_database_flattened(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_hive_database), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = hive_metastore.HiveDatabase() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_hive_database( + hive_database=hive_metastore.HiveDatabase(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].hive_database + mock_val = hive_metastore.HiveDatabase(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +def test_update_hive_database_flattened_error(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_hive_database( + hive_metastore.UpdateHiveDatabaseRequest(), + hive_database=hive_metastore.HiveDatabase(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_hive_database_flattened_async(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_hive_database), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = hive_metastore.HiveDatabase() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hive_metastore.HiveDatabase() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_hive_database( + hive_database=hive_metastore.HiveDatabase(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].hive_database + mock_val = hive_metastore.HiveDatabase(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_update_hive_database_flattened_error_async(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_hive_database( + hive_metastore.UpdateHiveDatabaseRequest(), + hive_database=hive_metastore.HiveDatabase(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + hive_metastore.DeleteHiveDatabaseRequest(), + {}, + ], +) +def test_delete_hive_database(request_type, transport: str = "grpc"): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_hive_database), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_hive_database(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = hive_metastore.DeleteHiveDatabaseRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_hive_database_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = hive_metastore.DeleteHiveDatabaseRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_hive_database), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_hive_database(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hive_metastore.DeleteHiveDatabaseRequest( + name="name_value", + ) + assert args[0] == request_msg + + +def test_delete_hive_database_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.delete_hive_database in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.delete_hive_database] = ( + mock_rpc + ) + request = {} + client.delete_hive_database(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_hive_database(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_hive_database_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.delete_hive_database + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.delete_hive_database + ] = mock_rpc + + request = {} + await client.delete_hive_database(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.delete_hive_database(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + hive_metastore.DeleteHiveDatabaseRequest(), + {}, + ], +) +async def test_delete_hive_database_async( + request_type, transport: str = "grpc_asyncio" +): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_hive_database), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_hive_database(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = hive_metastore.DeleteHiveDatabaseRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_hive_database_field_headers(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = hive_metastore.DeleteHiveDatabaseRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_hive_database), "__call__" + ) as call: + call.return_value = None + client.delete_hive_database(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_hive_database_field_headers_async(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = hive_metastore.DeleteHiveDatabaseRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_hive_database), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_hive_database(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_delete_hive_database_flattened(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_hive_database), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_hive_database( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_delete_hive_database_flattened_error(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_hive_database( + hive_metastore.DeleteHiveDatabaseRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_hive_database_flattened_async(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_hive_database), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_hive_database( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_delete_hive_database_flattened_error_async(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_hive_database( + hive_metastore.DeleteHiveDatabaseRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + hive_metastore.CreateHiveTableRequest(), + {}, + ], +) +def test_create_hive_table(request_type, transport: str = "grpc"): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_hive_table), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = hive_metastore.HiveTable( + name="name_value", + description="description_value", + view_original_text="view_original_text_value", + view_expanded_text="view_expanded_text_value", + table_type="table_type_value", + ) + response = client.create_hive_table(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = hive_metastore.CreateHiveTableRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, hive_metastore.HiveTable) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.view_original_text == "view_original_text_value" + assert response.view_expanded_text == "view_expanded_text_value" + assert response.table_type == "table_type_value" + + +def test_create_hive_table_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = hive_metastore.CreateHiveTableRequest( + parent="parent_value", + hive_table_id="hive_table_id_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_hive_table), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_hive_table(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hive_metastore.CreateHiveTableRequest( + parent="parent_value", + hive_table_id="hive_table_id_value", + ) + assert args[0] == request_msg + + +def test_create_hive_table_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_hive_table in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.create_hive_table] = ( + mock_rpc + ) + request = {} + client.create_hive_table(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_hive_table(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_hive_table_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.create_hive_table + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.create_hive_table + ] = mock_rpc + + request = {} + await client.create_hive_table(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.create_hive_table(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + hive_metastore.CreateHiveTableRequest(), + {}, + ], +) +async def test_create_hive_table_async(request_type, transport: str = "grpc_asyncio"): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_hive_table), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hive_metastore.HiveTable( + name="name_value", + description="description_value", + view_original_text="view_original_text_value", + view_expanded_text="view_expanded_text_value", + table_type="table_type_value", + ) + ) + response = await client.create_hive_table(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = hive_metastore.CreateHiveTableRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, hive_metastore.HiveTable) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.view_original_text == "view_original_text_value" + assert response.view_expanded_text == "view_expanded_text_value" + assert response.table_type == "table_type_value" + + +def test_create_hive_table_field_headers(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = hive_metastore.CreateHiveTableRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_hive_table), "__call__" + ) as call: + call.return_value = hive_metastore.HiveTable() + client.create_hive_table(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_create_hive_table_field_headers_async(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = hive_metastore.CreateHiveTableRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_hive_table), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hive_metastore.HiveTable() + ) + await client.create_hive_table(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_create_hive_table_flattened(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_hive_table), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = hive_metastore.HiveTable() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_hive_table( + parent="parent_value", + hive_table=hive_metastore.HiveTable(name="name_value"), + hive_table_id="hive_table_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].hive_table + mock_val = hive_metastore.HiveTable(name="name_value") + assert arg == mock_val + arg = args[0].hive_table_id + mock_val = "hive_table_id_value" + assert arg == mock_val + + +def test_create_hive_table_flattened_error(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_hive_table( + hive_metastore.CreateHiveTableRequest(), + parent="parent_value", + hive_table=hive_metastore.HiveTable(name="name_value"), + hive_table_id="hive_table_id_value", + ) + + +@pytest.mark.asyncio +async def test_create_hive_table_flattened_async(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_hive_table), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = hive_metastore.HiveTable() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hive_metastore.HiveTable() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_hive_table( + parent="parent_value", + hive_table=hive_metastore.HiveTable(name="name_value"), + hive_table_id="hive_table_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].hive_table + mock_val = hive_metastore.HiveTable(name="name_value") + assert arg == mock_val + arg = args[0].hive_table_id + mock_val = "hive_table_id_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_hive_table_flattened_error_async(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_hive_table( + hive_metastore.CreateHiveTableRequest(), + parent="parent_value", + hive_table=hive_metastore.HiveTable(name="name_value"), + hive_table_id="hive_table_id_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + hive_metastore.GetHiveTableRequest(), + {}, + ], +) +def test_get_hive_table(request_type, transport: str = "grpc"): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_hive_table), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = hive_metastore.HiveTable( + name="name_value", + description="description_value", + view_original_text="view_original_text_value", + view_expanded_text="view_expanded_text_value", + table_type="table_type_value", + ) + response = client.get_hive_table(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = hive_metastore.GetHiveTableRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, hive_metastore.HiveTable) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.view_original_text == "view_original_text_value" + assert response.view_expanded_text == "view_expanded_text_value" + assert response.table_type == "table_type_value" + + +def test_get_hive_table_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = hive_metastore.GetHiveTableRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_hive_table), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_hive_table(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hive_metastore.GetHiveTableRequest( + name="name_value", + ) + assert args[0] == request_msg + + +def test_get_hive_table_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_hive_table in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_hive_table] = mock_rpc + request = {} + client.get_hive_table(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_hive_table(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_hive_table_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.get_hive_table + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.get_hive_table + ] = mock_rpc + + request = {} + await client.get_hive_table(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_hive_table(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + hive_metastore.GetHiveTableRequest(), + {}, + ], +) +async def test_get_hive_table_async(request_type, transport: str = "grpc_asyncio"): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_hive_table), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hive_metastore.HiveTable( + name="name_value", + description="description_value", + view_original_text="view_original_text_value", + view_expanded_text="view_expanded_text_value", + table_type="table_type_value", + ) + ) + response = await client.get_hive_table(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = hive_metastore.GetHiveTableRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, hive_metastore.HiveTable) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.view_original_text == "view_original_text_value" + assert response.view_expanded_text == "view_expanded_text_value" + assert response.table_type == "table_type_value" + + +def test_get_hive_table_field_headers(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = hive_metastore.GetHiveTableRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_hive_table), "__call__") as call: + call.return_value = hive_metastore.HiveTable() + client.get_hive_table(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_hive_table_field_headers_async(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = hive_metastore.GetHiveTableRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_hive_table), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hive_metastore.HiveTable() + ) + await client.get_hive_table(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_get_hive_table_flattened(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_hive_table), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = hive_metastore.HiveTable() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_hive_table( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_get_hive_table_flattened_error(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_hive_table( + hive_metastore.GetHiveTableRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_hive_table_flattened_async(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_hive_table), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = hive_metastore.HiveTable() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hive_metastore.HiveTable() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_hive_table( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_hive_table_flattened_error_async(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_hive_table( + hive_metastore.GetHiveTableRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + hive_metastore.ListHiveTablesRequest(), + {}, + ], +) +def test_list_hive_tables(request_type, transport: str = "grpc"): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_hive_tables), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = hive_metastore.ListHiveTablesResponse( + next_page_token="next_page_token_value", + ) + response = client.list_hive_tables(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = hive_metastore.ListHiveTablesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListHiveTablesPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_hive_tables_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = hive_metastore.ListHiveTablesRequest( + parent="parent_value", + page_token="page_token_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_hive_tables), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_hive_tables(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hive_metastore.ListHiveTablesRequest( + parent="parent_value", + page_token="page_token_value", + ) + assert args[0] == request_msg + + +def test_list_hive_tables_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_hive_tables in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list_hive_tables] = ( + mock_rpc + ) + request = {} + client.list_hive_tables(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_hive_tables(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_hive_tables_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.list_hive_tables + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_hive_tables + ] = mock_rpc + + request = {} + await client.list_hive_tables(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_hive_tables(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + hive_metastore.ListHiveTablesRequest(), + {}, + ], +) +async def test_list_hive_tables_async(request_type, transport: str = "grpc_asyncio"): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_hive_tables), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hive_metastore.ListHiveTablesResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_hive_tables(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = hive_metastore.ListHiveTablesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListHiveTablesAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_hive_tables_field_headers(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = hive_metastore.ListHiveTablesRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_hive_tables), "__call__") as call: + call.return_value = hive_metastore.ListHiveTablesResponse() + client.list_hive_tables(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_hive_tables_field_headers_async(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = hive_metastore.ListHiveTablesRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_hive_tables), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hive_metastore.ListHiveTablesResponse() + ) + await client.list_hive_tables(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_list_hive_tables_flattened(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_hive_tables), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = hive_metastore.ListHiveTablesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_hive_tables( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +def test_list_hive_tables_flattened_error(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_hive_tables( + hive_metastore.ListHiveTablesRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_hive_tables_flattened_async(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_hive_tables), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = hive_metastore.ListHiveTablesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hive_metastore.ListHiveTablesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_hive_tables( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_hive_tables_flattened_error_async(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_hive_tables( + hive_metastore.ListHiveTablesRequest(), + parent="parent_value", + ) + + +def test_list_hive_tables_pager(transport_name: str = "grpc"): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_hive_tables), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + hive_metastore.ListHiveTablesResponse( + tables=[ + hive_metastore.HiveTable(), + hive_metastore.HiveTable(), + hive_metastore.HiveTable(), + ], + next_page_token="abc", + ), + hive_metastore.ListHiveTablesResponse( + tables=[], + next_page_token="def", + ), + hive_metastore.ListHiveTablesResponse( + tables=[ + hive_metastore.HiveTable(), + ], + next_page_token="ghi", + ), + hive_metastore.ListHiveTablesResponse( + tables=[ + hive_metastore.HiveTable(), + hive_metastore.HiveTable(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_hive_tables(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, hive_metastore.HiveTable) for i in results) + + +def test_list_hive_tables_pages(transport_name: str = "grpc"): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_hive_tables), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + hive_metastore.ListHiveTablesResponse( + tables=[ + hive_metastore.HiveTable(), + hive_metastore.HiveTable(), + hive_metastore.HiveTable(), + ], + next_page_token="abc", + ), + hive_metastore.ListHiveTablesResponse( + tables=[], + next_page_token="def", + ), + hive_metastore.ListHiveTablesResponse( + tables=[ + hive_metastore.HiveTable(), + ], + next_page_token="ghi", + ), + hive_metastore.ListHiveTablesResponse( + tables=[ + hive_metastore.HiveTable(), + hive_metastore.HiveTable(), + ], + ), + RuntimeError, + ) + pages = list(client.list_hive_tables(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_hive_tables_async_pager(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_hive_tables), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + hive_metastore.ListHiveTablesResponse( + tables=[ + hive_metastore.HiveTable(), + hive_metastore.HiveTable(), + hive_metastore.HiveTable(), + ], + next_page_token="abc", + ), + hive_metastore.ListHiveTablesResponse( + tables=[], + next_page_token="def", + ), + hive_metastore.ListHiveTablesResponse( + tables=[ + hive_metastore.HiveTable(), + ], + next_page_token="ghi", + ), + hive_metastore.ListHiveTablesResponse( + tables=[ + hive_metastore.HiveTable(), + hive_metastore.HiveTable(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_hive_tables( + request={}, + ) + assert async_pager.next_page_token == "abc" + assert str(async_pager).startswith(f"{async_pager.__class__.__name__}<") + + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, hive_metastore.HiveTable) for i in responses) + + +@pytest.mark.asyncio +async def test_list_hive_tables_async_pages(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_hive_tables), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + hive_metastore.ListHiveTablesResponse( + tables=[ + hive_metastore.HiveTable(), + hive_metastore.HiveTable(), + hive_metastore.HiveTable(), + ], + next_page_token="abc", + ), + hive_metastore.ListHiveTablesResponse( + tables=[], + next_page_token="def", + ), + hive_metastore.ListHiveTablesResponse( + tables=[ + hive_metastore.HiveTable(), + ], + next_page_token="ghi", + ), + hive_metastore.ListHiveTablesResponse( + tables=[ + hive_metastore.HiveTable(), + hive_metastore.HiveTable(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_hive_tables(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + hive_metastore.UpdateHiveTableRequest(), + {}, + ], +) +def test_update_hive_table(request_type, transport: str = "grpc"): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_hive_table), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = hive_metastore.HiveTable( + name="name_value", + description="description_value", + view_original_text="view_original_text_value", + view_expanded_text="view_expanded_text_value", + table_type="table_type_value", + ) + response = client.update_hive_table(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = hive_metastore.UpdateHiveTableRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, hive_metastore.HiveTable) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.view_original_text == "view_original_text_value" + assert response.view_expanded_text == "view_expanded_text_value" + assert response.table_type == "table_type_value" + + +def test_update_hive_table_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = hive_metastore.UpdateHiveTableRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_hive_table), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.update_hive_table(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hive_metastore.UpdateHiveTableRequest() + assert args[0] == request_msg + + +def test_update_hive_table_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_hive_table in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_hive_table] = ( + mock_rpc + ) + request = {} + client.update_hive_table(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_hive_table(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_hive_table_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.update_hive_table + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.update_hive_table + ] = mock_rpc + + request = {} + await client.update_hive_table(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_hive_table(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + hive_metastore.UpdateHiveTableRequest(), + {}, + ], +) +async def test_update_hive_table_async(request_type, transport: str = "grpc_asyncio"): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_hive_table), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hive_metastore.HiveTable( + name="name_value", + description="description_value", + view_original_text="view_original_text_value", + view_expanded_text="view_expanded_text_value", + table_type="table_type_value", + ) + ) + response = await client.update_hive_table(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = hive_metastore.UpdateHiveTableRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, hive_metastore.HiveTable) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.view_original_text == "view_original_text_value" + assert response.view_expanded_text == "view_expanded_text_value" + assert response.table_type == "table_type_value" + + +def test_update_hive_table_field_headers(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = hive_metastore.UpdateHiveTableRequest() + + request.hive_table.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_hive_table), "__call__" + ) as call: + call.return_value = hive_metastore.HiveTable() + client.update_hive_table(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "hive_table.name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_hive_table_field_headers_async(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = hive_metastore.UpdateHiveTableRequest() + + request.hive_table.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_hive_table), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hive_metastore.HiveTable() + ) + await client.update_hive_table(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "hive_table.name=name_value", + ) in kw["metadata"] + + +def test_update_hive_table_flattened(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_hive_table), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = hive_metastore.HiveTable() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_hive_table( + hive_table=hive_metastore.HiveTable(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].hive_table + mock_val = hive_metastore.HiveTable(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +def test_update_hive_table_flattened_error(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_hive_table( + hive_metastore.UpdateHiveTableRequest(), + hive_table=hive_metastore.HiveTable(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_hive_table_flattened_async(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_hive_table), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = hive_metastore.HiveTable() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hive_metastore.HiveTable() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_hive_table( + hive_table=hive_metastore.HiveTable(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].hive_table + mock_val = hive_metastore.HiveTable(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_update_hive_table_flattened_error_async(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_hive_table( + hive_metastore.UpdateHiveTableRequest(), + hive_table=hive_metastore.HiveTable(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + hive_metastore.DeleteHiveTableRequest(), + {}, + ], +) +def test_delete_hive_table(request_type, transport: str = "grpc"): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_hive_table), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_hive_table(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = hive_metastore.DeleteHiveTableRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_hive_table_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = hive_metastore.DeleteHiveTableRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_hive_table), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_hive_table(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hive_metastore.DeleteHiveTableRequest( + name="name_value", + ) + assert args[0] == request_msg + + +def test_delete_hive_table_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_hive_table in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.delete_hive_table] = ( + mock_rpc + ) + request = {} + client.delete_hive_table(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_hive_table(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_hive_table_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.delete_hive_table + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.delete_hive_table + ] = mock_rpc + + request = {} + await client.delete_hive_table(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.delete_hive_table(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + hive_metastore.DeleteHiveTableRequest(), + {}, + ], +) +async def test_delete_hive_table_async(request_type, transport: str = "grpc_asyncio"): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_hive_table), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_hive_table(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = hive_metastore.DeleteHiveTableRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_hive_table_field_headers(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = hive_metastore.DeleteHiveTableRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_hive_table), "__call__" + ) as call: + call.return_value = None + client.delete_hive_table(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_hive_table_field_headers_async(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = hive_metastore.DeleteHiveTableRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_hive_table), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_hive_table(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_delete_hive_table_flattened(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_hive_table), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_hive_table( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_delete_hive_table_flattened_error(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_hive_table( + hive_metastore.DeleteHiveTableRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_hive_table_flattened_async(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_hive_table), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_hive_table( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_delete_hive_table_flattened_error_async(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_hive_table( + hive_metastore.DeleteHiveTableRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + hive_metastore.BatchCreatePartitionsRequest(), + {}, + ], +) +def test_batch_create_partitions(request_type, transport: str = "grpc"): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_partitions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = hive_metastore.BatchCreatePartitionsResponse() + response = client.batch_create_partitions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = hive_metastore.BatchCreatePartitionsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, hive_metastore.BatchCreatePartitionsResponse) + + +def test_batch_create_partitions_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = hive_metastore.BatchCreatePartitionsRequest( + parent="parent_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_partitions), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.batch_create_partitions(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hive_metastore.BatchCreatePartitionsRequest( + parent="parent_value", + ) + assert args[0] == request_msg + + +def test_batch_create_partitions_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.batch_create_partitions + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.batch_create_partitions + ] = mock_rpc + request = {} + client.batch_create_partitions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.batch_create_partitions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_batch_create_partitions_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.batch_create_partitions + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.batch_create_partitions + ] = mock_rpc + + request = {} + await client.batch_create_partitions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.batch_create_partitions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + hive_metastore.BatchCreatePartitionsRequest(), + {}, + ], +) +async def test_batch_create_partitions_async( + request_type, transport: str = "grpc_asyncio" +): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_partitions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hive_metastore.BatchCreatePartitionsResponse() + ) + response = await client.batch_create_partitions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = hive_metastore.BatchCreatePartitionsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, hive_metastore.BatchCreatePartitionsResponse) + + +def test_batch_create_partitions_field_headers(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = hive_metastore.BatchCreatePartitionsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_partitions), "__call__" + ) as call: + call.return_value = hive_metastore.BatchCreatePartitionsResponse() + client.batch_create_partitions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_batch_create_partitions_field_headers_async(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = hive_metastore.BatchCreatePartitionsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_partitions), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hive_metastore.BatchCreatePartitionsResponse() + ) + await client.batch_create_partitions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_batch_create_partitions_flattened(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_partitions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = hive_metastore.BatchCreatePartitionsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.batch_create_partitions( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +def test_batch_create_partitions_flattened_error(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.batch_create_partitions( + hive_metastore.BatchCreatePartitionsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_batch_create_partitions_flattened_async(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_partitions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = hive_metastore.BatchCreatePartitionsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hive_metastore.BatchCreatePartitionsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.batch_create_partitions( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_batch_create_partitions_flattened_error_async(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.batch_create_partitions( + hive_metastore.BatchCreatePartitionsRequest(), + parent="parent_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + hive_metastore.BatchDeletePartitionsRequest(), + {}, + ], +) +def test_batch_delete_partitions(request_type, transport: str = "grpc"): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_delete_partitions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.batch_delete_partitions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = hive_metastore.BatchDeletePartitionsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_batch_delete_partitions_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = hive_metastore.BatchDeletePartitionsRequest( + parent="parent_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_delete_partitions), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.batch_delete_partitions(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hive_metastore.BatchDeletePartitionsRequest( + parent="parent_value", + ) + assert args[0] == request_msg + + +def test_batch_delete_partitions_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.batch_delete_partitions + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.batch_delete_partitions + ] = mock_rpc + request = {} + client.batch_delete_partitions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.batch_delete_partitions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_batch_delete_partitions_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.batch_delete_partitions + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.batch_delete_partitions + ] = mock_rpc + + request = {} + await client.batch_delete_partitions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.batch_delete_partitions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + hive_metastore.BatchDeletePartitionsRequest(), + {}, + ], +) +async def test_batch_delete_partitions_async( + request_type, transport: str = "grpc_asyncio" +): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_delete_partitions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.batch_delete_partitions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = hive_metastore.BatchDeletePartitionsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_batch_delete_partitions_field_headers(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = hive_metastore.BatchDeletePartitionsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_delete_partitions), "__call__" + ) as call: + call.return_value = None + client.batch_delete_partitions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_batch_delete_partitions_field_headers_async(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = hive_metastore.BatchDeletePartitionsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_delete_partitions), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.batch_delete_partitions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_batch_delete_partitions_flattened(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_delete_partitions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.batch_delete_partitions( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +def test_batch_delete_partitions_flattened_error(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.batch_delete_partitions( + hive_metastore.BatchDeletePartitionsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_batch_delete_partitions_flattened_async(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_delete_partitions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.batch_delete_partitions( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_batch_delete_partitions_flattened_error_async(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.batch_delete_partitions( + hive_metastore.BatchDeletePartitionsRequest(), + parent="parent_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + hive_metastore.BatchUpdatePartitionsRequest(), + {}, + ], +) +def test_batch_update_partitions(request_type, transport: str = "grpc"): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_partitions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = hive_metastore.BatchUpdatePartitionsResponse() + response = client.batch_update_partitions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = hive_metastore.BatchUpdatePartitionsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, hive_metastore.BatchUpdatePartitionsResponse) + + +def test_batch_update_partitions_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = hive_metastore.BatchUpdatePartitionsRequest( + parent="parent_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_partitions), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.batch_update_partitions(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hive_metastore.BatchUpdatePartitionsRequest( + parent="parent_value", + ) + assert args[0] == request_msg + + +def test_batch_update_partitions_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.batch_update_partitions + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.batch_update_partitions + ] = mock_rpc + request = {} + client.batch_update_partitions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.batch_update_partitions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_batch_update_partitions_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.batch_update_partitions + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.batch_update_partitions + ] = mock_rpc + + request = {} + await client.batch_update_partitions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.batch_update_partitions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + hive_metastore.BatchUpdatePartitionsRequest(), + {}, + ], +) +async def test_batch_update_partitions_async( + request_type, transport: str = "grpc_asyncio" +): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_partitions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hive_metastore.BatchUpdatePartitionsResponse() + ) + response = await client.batch_update_partitions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = hive_metastore.BatchUpdatePartitionsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, hive_metastore.BatchUpdatePartitionsResponse) + + +def test_batch_update_partitions_field_headers(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = hive_metastore.BatchUpdatePartitionsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_partitions), "__call__" + ) as call: + call.return_value = hive_metastore.BatchUpdatePartitionsResponse() + client.batch_update_partitions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_batch_update_partitions_field_headers_async(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = hive_metastore.BatchUpdatePartitionsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_partitions), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hive_metastore.BatchUpdatePartitionsResponse() + ) + await client.batch_update_partitions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_batch_update_partitions_flattened(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_partitions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = hive_metastore.BatchUpdatePartitionsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.batch_update_partitions( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +def test_batch_update_partitions_flattened_error(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.batch_update_partitions( + hive_metastore.BatchUpdatePartitionsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_batch_update_partitions_flattened_async(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_partitions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = hive_metastore.BatchUpdatePartitionsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hive_metastore.BatchUpdatePartitionsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.batch_update_partitions( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_batch_update_partitions_flattened_error_async(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.batch_update_partitions( + hive_metastore.BatchUpdatePartitionsRequest(), + parent="parent_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + hive_metastore.ListPartitionsRequest(), + {}, + ], +) +def test_list_partitions(request_type, transport: str = "grpc"): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_partitions), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = iter([hive_metastore.ListPartitionsResponse()]) + response = client.list_partitions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = hive_metastore.ListPartitionsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + for message in response: + assert isinstance(message, hive_metastore.ListPartitionsResponse) + + +def test_list_partitions_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = hive_metastore.ListPartitionsRequest( + parent="parent_value", + filter="filter_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_partitions), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_partitions(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hive_metastore.ListPartitionsRequest( + parent="parent_value", + filter="filter_value", + ) + assert args[0] == request_msg + + +def test_list_partitions_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_partitions in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list_partitions] = mock_rpc + request = {} + client.list_partitions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_partitions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_partitions_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.list_partitions + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_partitions + ] = mock_rpc + + request = {} + await client.list_partitions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_partitions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + hive_metastore.ListPartitionsRequest(), + {}, + ], +) +async def test_list_partitions_async(request_type, transport: str = "grpc_asyncio"): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_partitions), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = mock.Mock(aio.UnaryStreamCall, autospec=True) + call.return_value.read = mock.AsyncMock( + side_effect=[hive_metastore.ListPartitionsResponse()] + ) + response = await client.list_partitions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = hive_metastore.ListPartitionsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + message = await response.read() + assert isinstance(message, hive_metastore.ListPartitionsResponse) + + +def test_list_partitions_field_headers(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = hive_metastore.ListPartitionsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_partitions), "__call__") as call: + call.return_value = iter([hive_metastore.ListPartitionsResponse()]) + client.list_partitions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_partitions_field_headers_async(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = hive_metastore.ListPartitionsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_partitions), "__call__") as call: + call.return_value = mock.Mock(aio.UnaryStreamCall, autospec=True) + call.return_value.read = mock.AsyncMock( + side_effect=[hive_metastore.ListPartitionsResponse()] + ) + await client.list_partitions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_list_partitions_flattened(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_partitions), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = iter([hive_metastore.ListPartitionsResponse()]) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_partitions( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +def test_list_partitions_flattened_error(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_partitions( + hive_metastore.ListPartitionsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_partitions_flattened_async(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_partitions), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = iter([hive_metastore.ListPartitionsResponse()]) + + call.return_value = mock.Mock(aio.UnaryStreamCall, autospec=True) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_partitions( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_partitions_flattened_error_async(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_partitions( + hive_metastore.ListPartitionsRequest(), + parent="parent_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + hive_metastore.FailoverHiveCatalogRequest(), + {}, + ], +) +def test_failover_hive_catalog(request_type, transport: str = "grpc"): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.failover_hive_catalog), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = hive_metastore.FailoverHiveCatalogResponse() + response = client.failover_hive_catalog(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = hive_metastore.FailoverHiveCatalogRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, hive_metastore.FailoverHiveCatalogResponse) + + +def test_failover_hive_catalog_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = hive_metastore.FailoverHiveCatalogRequest( + name="name_value", + primary_replica="primary_replica_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.failover_hive_catalog), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.failover_hive_catalog(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hive_metastore.FailoverHiveCatalogRequest( + name="name_value", + primary_replica="primary_replica_value", + ) + assert args[0] == request_msg + + +def test_failover_hive_catalog_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.failover_hive_catalog + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.failover_hive_catalog] = ( + mock_rpc + ) + request = {} + client.failover_hive_catalog(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.failover_hive_catalog(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_failover_hive_catalog_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.failover_hive_catalog + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.failover_hive_catalog + ] = mock_rpc + + request = {} + await client.failover_hive_catalog(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.failover_hive_catalog(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + hive_metastore.FailoverHiveCatalogRequest(), + {}, + ], +) +async def test_failover_hive_catalog_async( + request_type, transport: str = "grpc_asyncio" +): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.failover_hive_catalog), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hive_metastore.FailoverHiveCatalogResponse() + ) + response = await client.failover_hive_catalog(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = hive_metastore.FailoverHiveCatalogRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, hive_metastore.FailoverHiveCatalogResponse) + + +def test_failover_hive_catalog_field_headers(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = hive_metastore.FailoverHiveCatalogRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.failover_hive_catalog), "__call__" + ) as call: + call.return_value = hive_metastore.FailoverHiveCatalogResponse() + client.failover_hive_catalog(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_failover_hive_catalog_field_headers_async(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = hive_metastore.FailoverHiveCatalogRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.failover_hive_catalog), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hive_metastore.FailoverHiveCatalogResponse() + ) + await client.failover_hive_catalog(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_failover_hive_catalog_flattened(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.failover_hive_catalog), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = hive_metastore.FailoverHiveCatalogResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.failover_hive_catalog( + name="name_value", + primary_replica="primary_replica_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + arg = args[0].primary_replica + mock_val = "primary_replica_value" + assert arg == mock_val + + +def test_failover_hive_catalog_flattened_error(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.failover_hive_catalog( + hive_metastore.FailoverHiveCatalogRequest(), + name="name_value", + primary_replica="primary_replica_value", + ) + + +@pytest.mark.asyncio +async def test_failover_hive_catalog_flattened_async(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.failover_hive_catalog), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = hive_metastore.FailoverHiveCatalogResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hive_metastore.FailoverHiveCatalogResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.failover_hive_catalog( + name="name_value", + primary_replica="primary_replica_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + arg = args[0].primary_replica + mock_val = "primary_replica_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_failover_hive_catalog_flattened_error_async(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.failover_hive_catalog( + hive_metastore.FailoverHiveCatalogRequest(), + name="name_value", + primary_replica="primary_replica_value", + ) + + +def test_create_hive_catalog_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_hive_catalog in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.create_hive_catalog] = ( + mock_rpc + ) + + request = {} + client.create_hive_catalog(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_hive_catalog(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_hive_catalog_rest_required_fields( + request_type=hive_metastore.CreateHiveCatalogRequest, +): + transport_class = transports.HiveMetastoreServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["hive_catalog_id"] = "" + request_init["primary_location"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + assert "hiveCatalogId" not in jsonified_request + assert "primaryLocation" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_hive_catalog._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "hiveCatalogId" in jsonified_request + assert jsonified_request["hiveCatalogId"] == request_init["hive_catalog_id"] + assert "primaryLocation" in jsonified_request + assert jsonified_request["primaryLocation"] == request_init["primary_location"] + + jsonified_request["parent"] = "parent_value" + jsonified_request["hiveCatalogId"] = "hive_catalog_id_value" + jsonified_request["primaryLocation"] = "primary_location_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_hive_catalog._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "hive_catalog_id", + "primary_location", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "hiveCatalogId" in jsonified_request + assert jsonified_request["hiveCatalogId"] == "hive_catalog_id_value" + assert "primaryLocation" in jsonified_request + assert jsonified_request["primaryLocation"] == "primary_location_value" + + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = hive_metastore.HiveCatalog() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = hive_metastore.HiveCatalog.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.create_hive_catalog(request) + + expected_params = [ + ( + "hiveCatalogId", + "", + ), + ( + "primaryLocation", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_create_hive_catalog_rest_unset_required_fields(): + transport = transports.HiveMetastoreServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_hive_catalog._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "hiveCatalogId", + "primaryLocation", + ) + ) + & set( + ( + "parent", + "hiveCatalog", + "hiveCatalogId", + "primaryLocation", + ) + ) + ) + + +def test_create_hive_catalog_rest_flattened(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = hive_metastore.HiveCatalog() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + hive_catalog=hive_metastore.HiveCatalog(name="name_value"), + hive_catalog_id="hive_catalog_id_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = hive_metastore.HiveCatalog.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_hive_catalog(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/hive/v1/{parent=projects/*}/catalogs" % client.transport._host, args[1] + ) + + +def test_create_hive_catalog_rest_flattened_error(transport: str = "rest"): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_hive_catalog( + hive_metastore.CreateHiveCatalogRequest(), + parent="parent_value", + hive_catalog=hive_metastore.HiveCatalog(name="name_value"), + hive_catalog_id="hive_catalog_id_value", + ) + + +def test_get_hive_catalog_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_hive_catalog in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_hive_catalog] = ( + mock_rpc + ) + + request = {} + client.get_hive_catalog(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_hive_catalog(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_hive_catalog_rest_required_fields( + request_type=hive_metastore.GetHiveCatalogRequest, +): + transport_class = transports.HiveMetastoreServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_hive_catalog._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_hive_catalog._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = hive_metastore.HiveCatalog() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = hive_metastore.HiveCatalog.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_hive_catalog(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_get_hive_catalog_rest_unset_required_fields(): + transport = transports.HiveMetastoreServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_hive_catalog._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_hive_catalog_rest_flattened(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = hive_metastore.HiveCatalog() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/catalogs/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = hive_metastore.HiveCatalog.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_hive_catalog(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/hive/v1/{name=projects/*/catalogs/*}" % client.transport._host, args[1] + ) + + +def test_get_hive_catalog_rest_flattened_error(transport: str = "rest"): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_hive_catalog( + hive_metastore.GetHiveCatalogRequest(), + name="name_value", + ) + + +def test_list_hive_catalogs_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_hive_catalogs in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list_hive_catalogs] = ( + mock_rpc + ) + + request = {} + client.list_hive_catalogs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_hive_catalogs(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_hive_catalogs_rest_required_fields( + request_type=hive_metastore.ListHiveCatalogsRequest, +): + transport_class = transports.HiveMetastoreServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_hive_catalogs._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_hive_catalogs._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = hive_metastore.ListHiveCatalogsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = hive_metastore.ListHiveCatalogsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_hive_catalogs(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_list_hive_catalogs_rest_unset_required_fields(): + transport = transports.HiveMetastoreServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_hive_catalogs._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +def test_list_hive_catalogs_rest_flattened(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = hive_metastore.ListHiveCatalogsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = hive_metastore.ListHiveCatalogsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_hive_catalogs(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/hive/v1/{parent=projects/*}/catalogs" % client.transport._host, args[1] + ) + + +def test_list_hive_catalogs_rest_flattened_error(transport: str = "rest"): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_hive_catalogs( + hive_metastore.ListHiveCatalogsRequest(), + parent="parent_value", + ) + + +def test_list_hive_catalogs_rest_pager(transport: str = "rest"): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + hive_metastore.ListHiveCatalogsResponse( + catalogs=[ + hive_metastore.HiveCatalog(), + hive_metastore.HiveCatalog(), + hive_metastore.HiveCatalog(), + ], + next_page_token="abc", + ), + hive_metastore.ListHiveCatalogsResponse( + catalogs=[], + next_page_token="def", + ), + hive_metastore.ListHiveCatalogsResponse( + catalogs=[ + hive_metastore.HiveCatalog(), + ], + next_page_token="ghi", + ), + hive_metastore.ListHiveCatalogsResponse( + catalogs=[ + hive_metastore.HiveCatalog(), + hive_metastore.HiveCatalog(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + hive_metastore.ListHiveCatalogsResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1"} + + pager = client.list_hive_catalogs(request=sample_request) + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, hive_metastore.HiveCatalog) for i in results) + + pages = list(client.list_hive_catalogs(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_update_hive_catalog_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.update_hive_catalog in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_hive_catalog] = ( + mock_rpc + ) + + request = {} + client.update_hive_catalog(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_hive_catalog(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_hive_catalog_rest_required_fields( + request_type=hive_metastore.UpdateHiveCatalogRequest, +): + transport_class = transports.HiveMetastoreServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_hive_catalog._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_hive_catalog._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = hive_metastore.HiveCatalog() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = hive_metastore.HiveCatalog.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.update_hive_catalog(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_update_hive_catalog_rest_unset_required_fields(): + transport = transports.HiveMetastoreServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_hive_catalog._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask",)) & set(("hiveCatalog",))) + + +def test_update_hive_catalog_rest_flattened(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = hive_metastore.HiveCatalog() + + # get arguments that satisfy an http rule for this method + sample_request = {"hive_catalog": {"name": "projects/sample1/catalogs/sample2"}} + + # get truthy value for each flattened field + mock_args = dict( + hive_catalog=hive_metastore.HiveCatalog(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = hive_metastore.HiveCatalog.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.update_hive_catalog(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/hive/v1/{hive_catalog.name=projects/*/catalogs/*}" + % client.transport._host, + args[1], + ) + + +def test_update_hive_catalog_rest_flattened_error(transport: str = "rest"): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_hive_catalog( + hive_metastore.UpdateHiveCatalogRequest(), + hive_catalog=hive_metastore.HiveCatalog(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_delete_hive_catalog_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.delete_hive_catalog in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.delete_hive_catalog] = ( + mock_rpc + ) + + request = {} + client.delete_hive_catalog(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_hive_catalog(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_hive_catalog_rest_required_fields( + request_type=hive_metastore.DeleteHiveCatalogRequest, +): + transport_class = transports.HiveMetastoreServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_hive_catalog._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_hive_catalog._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_hive_catalog(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_delete_hive_catalog_rest_unset_required_fields(): + transport = transports.HiveMetastoreServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_hive_catalog._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_delete_hive_catalog_rest_flattened(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/catalogs/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_hive_catalog(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/hive/v1/{name=projects/*/catalogs/*}" % client.transport._host, args[1] + ) + + +def test_delete_hive_catalog_rest_flattened_error(transport: str = "rest"): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_hive_catalog( + hive_metastore.DeleteHiveCatalogRequest(), + name="name_value", + ) + + +def test_create_hive_database_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_hive_database in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.create_hive_database] = ( + mock_rpc + ) + + request = {} + client.create_hive_database(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_hive_database(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_hive_database_rest_required_fields( + request_type=hive_metastore.CreateHiveDatabaseRequest, +): + transport_class = transports.HiveMetastoreServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["hive_database_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + assert "hiveDatabaseId" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_hive_database._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "hiveDatabaseId" in jsonified_request + assert jsonified_request["hiveDatabaseId"] == request_init["hive_database_id"] + + jsonified_request["parent"] = "parent_value" + jsonified_request["hiveDatabaseId"] = "hive_database_id_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_hive_database._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("hive_database_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "hiveDatabaseId" in jsonified_request + assert jsonified_request["hiveDatabaseId"] == "hive_database_id_value" + + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = hive_metastore.HiveDatabase() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = hive_metastore.HiveDatabase.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.create_hive_database(request) + + expected_params = [ + ( + "hiveDatabaseId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_create_hive_database_rest_unset_required_fields(): + transport = transports.HiveMetastoreServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_hive_database._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("hiveDatabaseId",)) + & set( + ( + "parent", + "hiveDatabase", + "hiveDatabaseId", + ) + ) + ) + + +def test_create_hive_database_rest_flattened(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = hive_metastore.HiveDatabase() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/catalogs/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + hive_database=hive_metastore.HiveDatabase(name="name_value"), + hive_database_id="hive_database_id_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = hive_metastore.HiveDatabase.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_hive_database(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/hive/v1/{parent=projects/*/catalogs/*}/databases" + % client.transport._host, + args[1], + ) + + +def test_create_hive_database_rest_flattened_error(transport: str = "rest"): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_hive_database( + hive_metastore.CreateHiveDatabaseRequest(), + parent="parent_value", + hive_database=hive_metastore.HiveDatabase(name="name_value"), + hive_database_id="hive_database_id_value", + ) + + +def test_get_hive_database_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_hive_database in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_hive_database] = ( + mock_rpc + ) + + request = {} + client.get_hive_database(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_hive_database(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_hive_database_rest_required_fields( + request_type=hive_metastore.GetHiveDatabaseRequest, +): + transport_class = transports.HiveMetastoreServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_hive_database._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_hive_database._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = hive_metastore.HiveDatabase() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = hive_metastore.HiveDatabase.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_hive_database(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_get_hive_database_rest_unset_required_fields(): + transport = transports.HiveMetastoreServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_hive_database._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_hive_database_rest_flattened(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = hive_metastore.HiveDatabase() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/catalogs/sample2/databases/sample3"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = hive_metastore.HiveDatabase.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_hive_database(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/hive/v1/{name=projects/*/catalogs/*/databases/*}" + % client.transport._host, + args[1], + ) + + +def test_get_hive_database_rest_flattened_error(transport: str = "rest"): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_hive_database( + hive_metastore.GetHiveDatabaseRequest(), + name="name_value", + ) + + +def test_list_hive_databases_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_hive_databases in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list_hive_databases] = ( + mock_rpc + ) + + request = {} + client.list_hive_databases(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_hive_databases(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_hive_databases_rest_required_fields( + request_type=hive_metastore.ListHiveDatabasesRequest, +): + transport_class = transports.HiveMetastoreServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_hive_databases._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_hive_databases._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = hive_metastore.ListHiveDatabasesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = hive_metastore.ListHiveDatabasesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_hive_databases(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_list_hive_databases_rest_unset_required_fields(): + transport = transports.HiveMetastoreServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_hive_databases._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +def test_list_hive_databases_rest_flattened(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = hive_metastore.ListHiveDatabasesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/catalogs/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = hive_metastore.ListHiveDatabasesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_hive_databases(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/hive/v1/{parent=projects/*/catalogs/*}/databases" + % client.transport._host, + args[1], + ) + + +def test_list_hive_databases_rest_flattened_error(transport: str = "rest"): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_hive_databases( + hive_metastore.ListHiveDatabasesRequest(), + parent="parent_value", + ) + + +def test_list_hive_databases_rest_pager(transport: str = "rest"): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + hive_metastore.ListHiveDatabasesResponse( + databases=[ + hive_metastore.HiveDatabase(), + hive_metastore.HiveDatabase(), + hive_metastore.HiveDatabase(), + ], + next_page_token="abc", + ), + hive_metastore.ListHiveDatabasesResponse( + databases=[], + next_page_token="def", + ), + hive_metastore.ListHiveDatabasesResponse( + databases=[ + hive_metastore.HiveDatabase(), + ], + next_page_token="ghi", + ), + hive_metastore.ListHiveDatabasesResponse( + databases=[ + hive_metastore.HiveDatabase(), + hive_metastore.HiveDatabase(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + hive_metastore.ListHiveDatabasesResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1/catalogs/sample2"} + + pager = client.list_hive_databases(request=sample_request) + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, hive_metastore.HiveDatabase) for i in results) + + pages = list(client.list_hive_databases(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_update_hive_database_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.update_hive_database in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_hive_database] = ( + mock_rpc + ) + + request = {} + client.update_hive_database(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_hive_database(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_hive_database_rest_required_fields( + request_type=hive_metastore.UpdateHiveDatabaseRequest, +): + transport_class = transports.HiveMetastoreServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_hive_database._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_hive_database._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = hive_metastore.HiveDatabase() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = hive_metastore.HiveDatabase.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.update_hive_database(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_update_hive_database_rest_unset_required_fields(): + transport = transports.HiveMetastoreServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_hive_database._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask",)) & set(("hiveDatabase",))) + + +def test_update_hive_database_rest_flattened(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = hive_metastore.HiveDatabase() + + # get arguments that satisfy an http rule for this method + sample_request = { + "hive_database": { + "name": "projects/sample1/catalogs/sample2/databases/sample3" + } + } + + # get truthy value for each flattened field + mock_args = dict( + hive_database=hive_metastore.HiveDatabase(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = hive_metastore.HiveDatabase.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.update_hive_database(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/hive/v1/{hive_database.name=projects/*/catalogs/*/databases/*}" + % client.transport._host, + args[1], + ) + + +def test_update_hive_database_rest_flattened_error(transport: str = "rest"): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_hive_database( + hive_metastore.UpdateHiveDatabaseRequest(), + hive_database=hive_metastore.HiveDatabase(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_delete_hive_database_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.delete_hive_database in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.delete_hive_database] = ( + mock_rpc + ) + + request = {} + client.delete_hive_database(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_hive_database(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_hive_database_rest_required_fields( + request_type=hive_metastore.DeleteHiveDatabaseRequest, +): + transport_class = transports.HiveMetastoreServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_hive_database._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_hive_database._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_hive_database(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_delete_hive_database_rest_unset_required_fields(): + transport = transports.HiveMetastoreServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_hive_database._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_delete_hive_database_rest_flattened(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/catalogs/sample2/databases/sample3"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_hive_database(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/hive/v1/{name=projects/*/catalogs/*/databases/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_hive_database_rest_flattened_error(transport: str = "rest"): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_hive_database( + hive_metastore.DeleteHiveDatabaseRequest(), + name="name_value", + ) + + +def test_create_hive_table_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_hive_table in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.create_hive_table] = ( + mock_rpc + ) + + request = {} + client.create_hive_table(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_hive_table(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_hive_table_rest_required_fields( + request_type=hive_metastore.CreateHiveTableRequest, +): + transport_class = transports.HiveMetastoreServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["hive_table_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + assert "hiveTableId" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_hive_table._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "hiveTableId" in jsonified_request + assert jsonified_request["hiveTableId"] == request_init["hive_table_id"] + + jsonified_request["parent"] = "parent_value" + jsonified_request["hiveTableId"] = "hive_table_id_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_hive_table._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("hive_table_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "hiveTableId" in jsonified_request + assert jsonified_request["hiveTableId"] == "hive_table_id_value" + + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = hive_metastore.HiveTable() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = hive_metastore.HiveTable.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.create_hive_table(request) + + expected_params = [ + ( + "hiveTableId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_create_hive_table_rest_unset_required_fields(): + transport = transports.HiveMetastoreServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_hive_table._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("hiveTableId",)) + & set( + ( + "parent", + "hiveTable", + "hiveTableId", + ) + ) + ) + + +def test_create_hive_table_rest_flattened(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = hive_metastore.HiveTable() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/catalogs/sample2/databases/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + hive_table=hive_metastore.HiveTable(name="name_value"), + hive_table_id="hive_table_id_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = hive_metastore.HiveTable.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_hive_table(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/hive/v1/{parent=projects/*/catalogs/*/databases/*}/tables" + % client.transport._host, + args[1], + ) + + +def test_create_hive_table_rest_flattened_error(transport: str = "rest"): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_hive_table( + hive_metastore.CreateHiveTableRequest(), + parent="parent_value", + hive_table=hive_metastore.HiveTable(name="name_value"), + hive_table_id="hive_table_id_value", + ) + + +def test_get_hive_table_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_hive_table in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_hive_table] = mock_rpc + + request = {} + client.get_hive_table(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_hive_table(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_hive_table_rest_required_fields( + request_type=hive_metastore.GetHiveTableRequest, +): + transport_class = transports.HiveMetastoreServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_hive_table._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_hive_table._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = hive_metastore.HiveTable() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = hive_metastore.HiveTable.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_hive_table(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_get_hive_table_rest_unset_required_fields(): + transport = transports.HiveMetastoreServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_hive_table._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_hive_table_rest_flattened(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = hive_metastore.HiveTable() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/catalogs/sample2/databases/sample3/tables/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = hive_metastore.HiveTable.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_hive_table(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/hive/v1/{name=projects/*/catalogs/*/databases/*/tables/*}" + % client.transport._host, + args[1], + ) + + +def test_get_hive_table_rest_flattened_error(transport: str = "rest"): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_hive_table( + hive_metastore.GetHiveTableRequest(), + name="name_value", + ) + + +def test_list_hive_tables_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_hive_tables in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list_hive_tables] = ( + mock_rpc + ) + + request = {} + client.list_hive_tables(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_hive_tables(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_hive_tables_rest_required_fields( + request_type=hive_metastore.ListHiveTablesRequest, +): + transport_class = transports.HiveMetastoreServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_hive_tables._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_hive_tables._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = hive_metastore.ListHiveTablesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = hive_metastore.ListHiveTablesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_hive_tables(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_list_hive_tables_rest_unset_required_fields(): + transport = transports.HiveMetastoreServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_hive_tables._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +def test_list_hive_tables_rest_flattened(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = hive_metastore.ListHiveTablesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/catalogs/sample2/databases/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = hive_metastore.ListHiveTablesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_hive_tables(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/hive/v1/{parent=projects/*/catalogs/*/databases/*}/tables" + % client.transport._host, + args[1], + ) + + +def test_list_hive_tables_rest_flattened_error(transport: str = "rest"): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_hive_tables( + hive_metastore.ListHiveTablesRequest(), + parent="parent_value", + ) + + +def test_list_hive_tables_rest_pager(transport: str = "rest"): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + hive_metastore.ListHiveTablesResponse( + tables=[ + hive_metastore.HiveTable(), + hive_metastore.HiveTable(), + hive_metastore.HiveTable(), + ], + next_page_token="abc", + ), + hive_metastore.ListHiveTablesResponse( + tables=[], + next_page_token="def", + ), + hive_metastore.ListHiveTablesResponse( + tables=[ + hive_metastore.HiveTable(), + ], + next_page_token="ghi", + ), + hive_metastore.ListHiveTablesResponse( + tables=[ + hive_metastore.HiveTable(), + hive_metastore.HiveTable(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + hive_metastore.ListHiveTablesResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = { + "parent": "projects/sample1/catalogs/sample2/databases/sample3" + } + + pager = client.list_hive_tables(request=sample_request) + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, hive_metastore.HiveTable) for i in results) + + pages = list(client.list_hive_tables(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_update_hive_table_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_hive_table in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_hive_table] = ( + mock_rpc + ) + + request = {} + client.update_hive_table(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_hive_table(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_hive_table_rest_required_fields( + request_type=hive_metastore.UpdateHiveTableRequest, +): + transport_class = transports.HiveMetastoreServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_hive_table._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_hive_table._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = hive_metastore.HiveTable() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = hive_metastore.HiveTable.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.update_hive_table(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_update_hive_table_rest_unset_required_fields(): + transport = transports.HiveMetastoreServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_hive_table._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask",)) & set(("hiveTable",))) + + +def test_update_hive_table_rest_flattened(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = hive_metastore.HiveTable() + + # get arguments that satisfy an http rule for this method + sample_request = { + "hive_table": { + "name": "projects/sample1/catalogs/sample2/databases/sample3/tables/sample4" + } + } + + # get truthy value for each flattened field + mock_args = dict( + hive_table=hive_metastore.HiveTable(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = hive_metastore.HiveTable.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.update_hive_table(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/hive/v1/{hive_table.name=projects/*/catalogs/*/databases/*/tables/*}" + % client.transport._host, + args[1], + ) + + +def test_update_hive_table_rest_flattened_error(transport: str = "rest"): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_hive_table( + hive_metastore.UpdateHiveTableRequest(), + hive_table=hive_metastore.HiveTable(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_delete_hive_table_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_hive_table in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.delete_hive_table] = ( + mock_rpc + ) + + request = {} + client.delete_hive_table(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_hive_table(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_hive_table_rest_required_fields( + request_type=hive_metastore.DeleteHiveTableRequest, +): + transport_class = transports.HiveMetastoreServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_hive_table._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_hive_table._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_hive_table(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_delete_hive_table_rest_unset_required_fields(): + transport = transports.HiveMetastoreServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_hive_table._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_delete_hive_table_rest_flattened(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/catalogs/sample2/databases/sample3/tables/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_hive_table(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/hive/v1/{name=projects/*/catalogs/*/databases/*/tables/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_hive_table_rest_flattened_error(transport: str = "rest"): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_hive_table( + hive_metastore.DeleteHiveTableRequest(), + name="name_value", + ) + + +def test_batch_create_partitions_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.batch_create_partitions + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.batch_create_partitions + ] = mock_rpc + + request = {} + client.batch_create_partitions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.batch_create_partitions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_batch_create_partitions_rest_required_fields( + request_type=hive_metastore.BatchCreatePartitionsRequest, +): + transport_class = transports.HiveMetastoreServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).batch_create_partitions._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).batch_create_partitions._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = hive_metastore.BatchCreatePartitionsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = hive_metastore.BatchCreatePartitionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.batch_create_partitions(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_batch_create_partitions_rest_unset_required_fields(): + transport = transports.HiveMetastoreServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.batch_create_partitions._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "requests", + ) + ) + ) + + +def test_batch_create_partitions_rest_flattened(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = hive_metastore.BatchCreatePartitionsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/catalogs/sample2/databases/sample3/tables/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = hive_metastore.BatchCreatePartitionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.batch_create_partitions(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/hive/v1/{parent=projects/*/catalogs/*/databases/*/tables/*}/partitions:batchCreate" + % client.transport._host, + args[1], + ) + + +def test_batch_create_partitions_rest_flattened_error(transport: str = "rest"): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.batch_create_partitions( + hive_metastore.BatchCreatePartitionsRequest(), + parent="parent_value", + ) + + +def test_batch_delete_partitions_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.batch_delete_partitions + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.batch_delete_partitions + ] = mock_rpc + + request = {} + client.batch_delete_partitions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.batch_delete_partitions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_batch_delete_partitions_rest_required_fields( + request_type=hive_metastore.BatchDeletePartitionsRequest, +): + transport_class = transports.HiveMetastoreServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).batch_delete_partitions._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).batch_delete_partitions._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.batch_delete_partitions(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_batch_delete_partitions_rest_unset_required_fields(): + transport = transports.HiveMetastoreServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.batch_delete_partitions._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "partitionValues", + ) + ) + ) + + +def test_batch_delete_partitions_rest_flattened(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/catalogs/sample2/databases/sample3/tables/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.batch_delete_partitions(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/hive/v1/{parent=projects/*/catalogs/*/databases/*/tables/*}/partitions:batchDelete" + % client.transport._host, + args[1], + ) + + +def test_batch_delete_partitions_rest_flattened_error(transport: str = "rest"): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.batch_delete_partitions( + hive_metastore.BatchDeletePartitionsRequest(), + parent="parent_value", + ) + + +def test_batch_update_partitions_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.batch_update_partitions + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.batch_update_partitions + ] = mock_rpc + + request = {} + client.batch_update_partitions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.batch_update_partitions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_batch_update_partitions_rest_required_fields( + request_type=hive_metastore.BatchUpdatePartitionsRequest, +): + transport_class = transports.HiveMetastoreServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).batch_update_partitions._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).batch_update_partitions._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = hive_metastore.BatchUpdatePartitionsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = hive_metastore.BatchUpdatePartitionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.batch_update_partitions(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_batch_update_partitions_rest_unset_required_fields(): + transport = transports.HiveMetastoreServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.batch_update_partitions._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "requests", + ) + ) + ) + + +def test_batch_update_partitions_rest_flattened(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = hive_metastore.BatchUpdatePartitionsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/catalogs/sample2/databases/sample3/tables/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = hive_metastore.BatchUpdatePartitionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.batch_update_partitions(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/hive/v1/{parent=projects/*/catalogs/*/databases/*/tables/*}/partitions:batchUpdate" + % client.transport._host, + args[1], + ) + + +def test_batch_update_partitions_rest_flattened_error(transport: str = "rest"): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.batch_update_partitions( + hive_metastore.BatchUpdatePartitionsRequest(), + parent="parent_value", + ) + + +def test_list_partitions_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_partitions in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list_partitions] = mock_rpc + + request = {} + client.list_partitions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_partitions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_partitions_rest_required_fields( + request_type=hive_metastore.ListPartitionsRequest, +): + transport_class = transports.HiveMetastoreServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_partitions._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_partitions._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("filter",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = hive_metastore.ListPartitionsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = hive_metastore.ListPartitionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + json_return_value = "[{}]".format(json_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + with mock.patch.object(response_value, "iter_content") as iter_content: + iter_content.return_value = iter(json_return_value) + response = client.list_partitions(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_list_partitions_rest_unset_required_fields(): + transport = transports.HiveMetastoreServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_partitions._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter",)) & set(("parent",))) + + +def test_list_partitions_rest_flattened(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = hive_metastore.ListPartitionsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/catalogs/sample2/databases/sample3/tables/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = hive_metastore.ListPartitionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + json_return_value = "[{}]".format(json_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + with mock.patch.object(response_value, "iter_content") as iter_content: + iter_content.return_value = iter(json_return_value) + client.list_partitions(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/hive/v1/{parent=projects/*/catalogs/*/databases/*/tables/*}/partitions:list" + % client.transport._host, + args[1], + ) + + +def test_list_partitions_rest_flattened_error(transport: str = "rest"): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_partitions( + hive_metastore.ListPartitionsRequest(), + parent="parent_value", + ) + + +def test_failover_hive_catalog_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.failover_hive_catalog + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.failover_hive_catalog] = ( + mock_rpc + ) + + request = {} + client.failover_hive_catalog(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.failover_hive_catalog(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_failover_hive_catalog_rest_required_fields( + request_type=hive_metastore.FailoverHiveCatalogRequest, +): + transport_class = transports.HiveMetastoreServiceRestTransport + + request_init = {} + request_init["name"] = "" + request_init["primary_replica"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).failover_hive_catalog._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + jsonified_request["primaryReplica"] = "primary_replica_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).failover_hive_catalog._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + assert "primaryReplica" in jsonified_request + assert jsonified_request["primaryReplica"] == "primary_replica_value" + + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = hive_metastore.FailoverHiveCatalogResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = hive_metastore.FailoverHiveCatalogResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.failover_hive_catalog(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_failover_hive_catalog_rest_unset_required_fields(): + transport = transports.HiveMetastoreServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.failover_hive_catalog._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "name", + "primaryReplica", + ) + ) + ) + + +def test_failover_hive_catalog_rest_flattened(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = hive_metastore.FailoverHiveCatalogResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/catalogs/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + primary_replica="primary_replica_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = hive_metastore.FailoverHiveCatalogResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.failover_hive_catalog(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/hive/v1/{name=projects/*/catalogs/*}:failover" % client.transport._host, + args[1], + ) + + +def test_failover_hive_catalog_rest_flattened_error(transport: str = "rest"): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.failover_hive_catalog( + hive_metastore.FailoverHiveCatalogRequest(), + name="name_value", + primary_replica="primary_replica_value", + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.HiveMetastoreServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.HiveMetastoreServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = HiveMetastoreServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.HiveMetastoreServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = HiveMetastoreServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = HiveMetastoreServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.HiveMetastoreServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = HiveMetastoreServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.HiveMetastoreServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = HiveMetastoreServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.HiveMetastoreServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.HiveMetastoreServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.HiveMetastoreServiceGrpcTransport, + transports.HiveMetastoreServiceGrpcAsyncIOTransport, + transports.HiveMetastoreServiceRestTransport, + ], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +def test_transport_kind_grpc(): + transport = HiveMetastoreServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_hive_catalog_empty_call_grpc(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_hive_catalog), "__call__" + ) as call: + call.return_value = hive_metastore.HiveCatalog() + client.create_hive_catalog(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hive_metastore.CreateHiveCatalogRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_hive_catalog_empty_call_grpc(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_hive_catalog), "__call__") as call: + call.return_value = hive_metastore.HiveCatalog() + client.get_hive_catalog(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hive_metastore.GetHiveCatalogRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_hive_catalogs_empty_call_grpc(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_hive_catalogs), "__call__" + ) as call: + call.return_value = hive_metastore.ListHiveCatalogsResponse() + client.list_hive_catalogs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hive_metastore.ListHiveCatalogsRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_hive_catalog_empty_call_grpc(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_hive_catalog), "__call__" + ) as call: + call.return_value = hive_metastore.HiveCatalog() + client.update_hive_catalog(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hive_metastore.UpdateHiveCatalogRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_hive_catalog_empty_call_grpc(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_hive_catalog), "__call__" + ) as call: + call.return_value = None + client.delete_hive_catalog(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hive_metastore.DeleteHiveCatalogRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_hive_database_empty_call_grpc(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_hive_database), "__call__" + ) as call: + call.return_value = hive_metastore.HiveDatabase() + client.create_hive_database(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hive_metastore.CreateHiveDatabaseRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_hive_database_empty_call_grpc(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_hive_database), "__call__" + ) as call: + call.return_value = hive_metastore.HiveDatabase() + client.get_hive_database(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hive_metastore.GetHiveDatabaseRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_hive_databases_empty_call_grpc(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_hive_databases), "__call__" + ) as call: + call.return_value = hive_metastore.ListHiveDatabasesResponse() + client.list_hive_databases(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hive_metastore.ListHiveDatabasesRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_hive_database_empty_call_grpc(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_hive_database), "__call__" + ) as call: + call.return_value = hive_metastore.HiveDatabase() + client.update_hive_database(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hive_metastore.UpdateHiveDatabaseRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_hive_database_empty_call_grpc(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_hive_database), "__call__" + ) as call: + call.return_value = None + client.delete_hive_database(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hive_metastore.DeleteHiveDatabaseRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_hive_table_empty_call_grpc(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_hive_table), "__call__" + ) as call: + call.return_value = hive_metastore.HiveTable() + client.create_hive_table(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hive_metastore.CreateHiveTableRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_hive_table_empty_call_grpc(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_hive_table), "__call__") as call: + call.return_value = hive_metastore.HiveTable() + client.get_hive_table(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hive_metastore.GetHiveTableRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_hive_tables_empty_call_grpc(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_hive_tables), "__call__") as call: + call.return_value = hive_metastore.ListHiveTablesResponse() + client.list_hive_tables(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hive_metastore.ListHiveTablesRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_hive_table_empty_call_grpc(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_hive_table), "__call__" + ) as call: + call.return_value = hive_metastore.HiveTable() + client.update_hive_table(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hive_metastore.UpdateHiveTableRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_hive_table_empty_call_grpc(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_hive_table), "__call__" + ) as call: + call.return_value = None + client.delete_hive_table(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hive_metastore.DeleteHiveTableRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_batch_create_partitions_empty_call_grpc(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_partitions), "__call__" + ) as call: + call.return_value = hive_metastore.BatchCreatePartitionsResponse() + client.batch_create_partitions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hive_metastore.BatchCreatePartitionsRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_batch_delete_partitions_empty_call_grpc(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.batch_delete_partitions), "__call__" + ) as call: + call.return_value = None + client.batch_delete_partitions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hive_metastore.BatchDeletePartitionsRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_batch_update_partitions_empty_call_grpc(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_partitions), "__call__" + ) as call: + call.return_value = hive_metastore.BatchUpdatePartitionsResponse() + client.batch_update_partitions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hive_metastore.BatchUpdatePartitionsRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_partitions_empty_call_grpc(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_partitions), "__call__") as call: + call.return_value = iter([hive_metastore.ListPartitionsResponse()]) + client.list_partitions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hive_metastore.ListPartitionsRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_failover_hive_catalog_empty_call_grpc(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.failover_hive_catalog), "__call__" + ) as call: + call.return_value = hive_metastore.FailoverHiveCatalogResponse() + client.failover_hive_catalog(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hive_metastore.FailoverHiveCatalogRequest() + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = HiveMetastoreServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_hive_catalog_empty_call_grpc_asyncio(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_hive_catalog), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hive_metastore.HiveCatalog( + name="name_value", + description="description_value", + location_uri="location_uri_value", + ) + ) + await client.create_hive_catalog(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hive_metastore.CreateHiveCatalogRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_hive_catalog_empty_call_grpc_asyncio(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_hive_catalog), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hive_metastore.HiveCatalog( + name="name_value", + description="description_value", + location_uri="location_uri_value", + ) + ) + await client.get_hive_catalog(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hive_metastore.GetHiveCatalogRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_hive_catalogs_empty_call_grpc_asyncio(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_hive_catalogs), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hive_metastore.ListHiveCatalogsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_hive_catalogs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hive_metastore.ListHiveCatalogsRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_hive_catalog_empty_call_grpc_asyncio(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_hive_catalog), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hive_metastore.HiveCatalog( + name="name_value", + description="description_value", + location_uri="location_uri_value", + ) + ) + await client.update_hive_catalog(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hive_metastore.UpdateHiveCatalogRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_hive_catalog_empty_call_grpc_asyncio(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_hive_catalog), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_hive_catalog(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hive_metastore.DeleteHiveCatalogRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_hive_database_empty_call_grpc_asyncio(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_hive_database), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hive_metastore.HiveDatabase( + name="name_value", + description="description_value", + location_uri="location_uri_value", + ) + ) + await client.create_hive_database(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hive_metastore.CreateHiveDatabaseRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_hive_database_empty_call_grpc_asyncio(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_hive_database), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hive_metastore.HiveDatabase( + name="name_value", + description="description_value", + location_uri="location_uri_value", + ) + ) + await client.get_hive_database(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hive_metastore.GetHiveDatabaseRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_hive_databases_empty_call_grpc_asyncio(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_hive_databases), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hive_metastore.ListHiveDatabasesResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_hive_databases(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hive_metastore.ListHiveDatabasesRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_hive_database_empty_call_grpc_asyncio(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_hive_database), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hive_metastore.HiveDatabase( + name="name_value", + description="description_value", + location_uri="location_uri_value", + ) + ) + await client.update_hive_database(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hive_metastore.UpdateHiveDatabaseRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_hive_database_empty_call_grpc_asyncio(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_hive_database), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_hive_database(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hive_metastore.DeleteHiveDatabaseRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_hive_table_empty_call_grpc_asyncio(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_hive_table), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hive_metastore.HiveTable( + name="name_value", + description="description_value", + view_original_text="view_original_text_value", + view_expanded_text="view_expanded_text_value", + table_type="table_type_value", + ) + ) + await client.create_hive_table(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hive_metastore.CreateHiveTableRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_hive_table_empty_call_grpc_asyncio(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_hive_table), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hive_metastore.HiveTable( + name="name_value", + description="description_value", + view_original_text="view_original_text_value", + view_expanded_text="view_expanded_text_value", + table_type="table_type_value", + ) + ) + await client.get_hive_table(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hive_metastore.GetHiveTableRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_hive_tables_empty_call_grpc_asyncio(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_hive_tables), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hive_metastore.ListHiveTablesResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_hive_tables(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hive_metastore.ListHiveTablesRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_hive_table_empty_call_grpc_asyncio(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_hive_table), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hive_metastore.HiveTable( + name="name_value", + description="description_value", + view_original_text="view_original_text_value", + view_expanded_text="view_expanded_text_value", + table_type="table_type_value", + ) + ) + await client.update_hive_table(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hive_metastore.UpdateHiveTableRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_hive_table_empty_call_grpc_asyncio(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_hive_table), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_hive_table(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hive_metastore.DeleteHiveTableRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_batch_create_partitions_empty_call_grpc_asyncio(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_partitions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hive_metastore.BatchCreatePartitionsResponse() + ) + await client.batch_create_partitions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hive_metastore.BatchCreatePartitionsRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_batch_delete_partitions_empty_call_grpc_asyncio(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.batch_delete_partitions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.batch_delete_partitions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hive_metastore.BatchDeletePartitionsRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_batch_update_partitions_empty_call_grpc_asyncio(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_partitions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hive_metastore.BatchUpdatePartitionsResponse() + ) + await client.batch_update_partitions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hive_metastore.BatchUpdatePartitionsRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_partitions_empty_call_grpc_asyncio(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_partitions), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = mock.Mock(aio.UnaryStreamCall, autospec=True) + call.return_value.read = mock.AsyncMock( + side_effect=[hive_metastore.ListPartitionsResponse()] + ) + await client.list_partitions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hive_metastore.ListPartitionsRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_failover_hive_catalog_empty_call_grpc_asyncio(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.failover_hive_catalog), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hive_metastore.FailoverHiveCatalogResponse() + ) + await client.failover_hive_catalog(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hive_metastore.FailoverHiveCatalogRequest() + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = HiveMetastoreServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_create_hive_catalog_rest_bad_request( + request_type=hive_metastore.CreateHiveCatalogRequest, +): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.create_hive_catalog(request) + + +@pytest.mark.parametrize( + "request_type", + [ + hive_metastore.CreateHiveCatalogRequest, + dict, + ], +) +def test_create_hive_catalog_rest_call_success(request_type): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1"} + request_init["hive_catalog"] = { + "name": "name_value", + "description": "description_value", + "location_uri": "location_uri_value", + "replicas": [{"region": "region_value", "state": 1}], + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = hive_metastore.CreateHiveCatalogRequest.meta.fields["hive_catalog"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["hive_catalog"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["hive_catalog"][field])): + del request_init["hive_catalog"][field][i][subfield] + else: + del request_init["hive_catalog"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = hive_metastore.HiveCatalog( + name="name_value", + description="description_value", + location_uri="location_uri_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = hive_metastore.HiveCatalog.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_hive_catalog(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, hive_metastore.HiveCatalog) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.location_uri == "location_uri_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_hive_catalog_rest_interceptors(null_interceptor): + transport = transports.HiveMetastoreServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.HiveMetastoreServiceRestInterceptor(), + ) + client = HiveMetastoreServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.HiveMetastoreServiceRestInterceptor, "post_create_hive_catalog" + ) as post, + mock.patch.object( + transports.HiveMetastoreServiceRestInterceptor, + "post_create_hive_catalog_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.HiveMetastoreServiceRestInterceptor, "pre_create_hive_catalog" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = hive_metastore.CreateHiveCatalogRequest.pb( + hive_metastore.CreateHiveCatalogRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = hive_metastore.HiveCatalog.to_json(hive_metastore.HiveCatalog()) + req.return_value.content = return_value + + request = hive_metastore.CreateHiveCatalogRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = hive_metastore.HiveCatalog() + post_with_metadata.return_value = hive_metastore.HiveCatalog(), metadata + + client.create_hive_catalog( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_hive_catalog_rest_bad_request( + request_type=hive_metastore.GetHiveCatalogRequest, +): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/catalogs/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_hive_catalog(request) + + +@pytest.mark.parametrize( + "request_type", + [ + hive_metastore.GetHiveCatalogRequest, + dict, + ], +) +def test_get_hive_catalog_rest_call_success(request_type): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/catalogs/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = hive_metastore.HiveCatalog( + name="name_value", + description="description_value", + location_uri="location_uri_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = hive_metastore.HiveCatalog.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_hive_catalog(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, hive_metastore.HiveCatalog) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.location_uri == "location_uri_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_hive_catalog_rest_interceptors(null_interceptor): + transport = transports.HiveMetastoreServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.HiveMetastoreServiceRestInterceptor(), + ) + client = HiveMetastoreServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.HiveMetastoreServiceRestInterceptor, "post_get_hive_catalog" + ) as post, + mock.patch.object( + transports.HiveMetastoreServiceRestInterceptor, + "post_get_hive_catalog_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.HiveMetastoreServiceRestInterceptor, "pre_get_hive_catalog" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = hive_metastore.GetHiveCatalogRequest.pb( + hive_metastore.GetHiveCatalogRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = hive_metastore.HiveCatalog.to_json(hive_metastore.HiveCatalog()) + req.return_value.content = return_value + + request = hive_metastore.GetHiveCatalogRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = hive_metastore.HiveCatalog() + post_with_metadata.return_value = hive_metastore.HiveCatalog(), metadata + + client.get_hive_catalog( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_hive_catalogs_rest_bad_request( + request_type=hive_metastore.ListHiveCatalogsRequest, +): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_hive_catalogs(request) + + +@pytest.mark.parametrize( + "request_type", + [ + hive_metastore.ListHiveCatalogsRequest, + dict, + ], +) +def test_list_hive_catalogs_rest_call_success(request_type): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = hive_metastore.ListHiveCatalogsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = hive_metastore.ListHiveCatalogsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_hive_catalogs(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListHiveCatalogsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_hive_catalogs_rest_interceptors(null_interceptor): + transport = transports.HiveMetastoreServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.HiveMetastoreServiceRestInterceptor(), + ) + client = HiveMetastoreServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.HiveMetastoreServiceRestInterceptor, "post_list_hive_catalogs" + ) as post, + mock.patch.object( + transports.HiveMetastoreServiceRestInterceptor, + "post_list_hive_catalogs_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.HiveMetastoreServiceRestInterceptor, "pre_list_hive_catalogs" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = hive_metastore.ListHiveCatalogsRequest.pb( + hive_metastore.ListHiveCatalogsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = hive_metastore.ListHiveCatalogsResponse.to_json( + hive_metastore.ListHiveCatalogsResponse() + ) + req.return_value.content = return_value + + request = hive_metastore.ListHiveCatalogsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = hive_metastore.ListHiveCatalogsResponse() + post_with_metadata.return_value = ( + hive_metastore.ListHiveCatalogsResponse(), + metadata, + ) + + client.list_hive_catalogs( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_hive_catalog_rest_bad_request( + request_type=hive_metastore.UpdateHiveCatalogRequest, +): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"hive_catalog": {"name": "projects/sample1/catalogs/sample2"}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.update_hive_catalog(request) + + +@pytest.mark.parametrize( + "request_type", + [ + hive_metastore.UpdateHiveCatalogRequest, + dict, + ], +) +def test_update_hive_catalog_rest_call_success(request_type): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"hive_catalog": {"name": "projects/sample1/catalogs/sample2"}} + request_init["hive_catalog"] = { + "name": "projects/sample1/catalogs/sample2", + "description": "description_value", + "location_uri": "location_uri_value", + "replicas": [{"region": "region_value", "state": 1}], + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = hive_metastore.UpdateHiveCatalogRequest.meta.fields["hive_catalog"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["hive_catalog"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["hive_catalog"][field])): + del request_init["hive_catalog"][field][i][subfield] + else: + del request_init["hive_catalog"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = hive_metastore.HiveCatalog( + name="name_value", + description="description_value", + location_uri="location_uri_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = hive_metastore.HiveCatalog.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.update_hive_catalog(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, hive_metastore.HiveCatalog) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.location_uri == "location_uri_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_hive_catalog_rest_interceptors(null_interceptor): + transport = transports.HiveMetastoreServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.HiveMetastoreServiceRestInterceptor(), + ) + client = HiveMetastoreServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.HiveMetastoreServiceRestInterceptor, "post_update_hive_catalog" + ) as post, + mock.patch.object( + transports.HiveMetastoreServiceRestInterceptor, + "post_update_hive_catalog_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.HiveMetastoreServiceRestInterceptor, "pre_update_hive_catalog" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = hive_metastore.UpdateHiveCatalogRequest.pb( + hive_metastore.UpdateHiveCatalogRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = hive_metastore.HiveCatalog.to_json(hive_metastore.HiveCatalog()) + req.return_value.content = return_value + + request = hive_metastore.UpdateHiveCatalogRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = hive_metastore.HiveCatalog() + post_with_metadata.return_value = hive_metastore.HiveCatalog(), metadata + + client.update_hive_catalog( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_hive_catalog_rest_bad_request( + request_type=hive_metastore.DeleteHiveCatalogRequest, +): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/catalogs/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_hive_catalog(request) + + +@pytest.mark.parametrize( + "request_type", + [ + hive_metastore.DeleteHiveCatalogRequest, + dict, + ], +) +def test_delete_hive_catalog_rest_call_success(request_type): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/catalogs/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "" + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_hive_catalog(request) + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_hive_catalog_rest_interceptors(null_interceptor): + transport = transports.HiveMetastoreServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.HiveMetastoreServiceRestInterceptor(), + ) + client = HiveMetastoreServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.HiveMetastoreServiceRestInterceptor, "pre_delete_hive_catalog" + ) as pre, + ): + pre.assert_not_called() + pb_message = hive_metastore.DeleteHiveCatalogRequest.pb( + hive_metastore.DeleteHiveCatalogRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + request = hive_metastore.DeleteHiveCatalogRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_hive_catalog( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_create_hive_database_rest_bad_request( + request_type=hive_metastore.CreateHiveDatabaseRequest, +): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/catalogs/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.create_hive_database(request) + + +@pytest.mark.parametrize( + "request_type", + [ + hive_metastore.CreateHiveDatabaseRequest, + dict, + ], +) +def test_create_hive_database_rest_call_success(request_type): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/catalogs/sample2"} + request_init["hive_database"] = { + "name": "name_value", + "description": "description_value", + "location_uri": "location_uri_value", + "parameters": {}, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = hive_metastore.CreateHiveDatabaseRequest.meta.fields["hive_database"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["hive_database"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["hive_database"][field])): + del request_init["hive_database"][field][i][subfield] + else: + del request_init["hive_database"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = hive_metastore.HiveDatabase( + name="name_value", + description="description_value", + location_uri="location_uri_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = hive_metastore.HiveDatabase.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_hive_database(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, hive_metastore.HiveDatabase) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.location_uri == "location_uri_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_hive_database_rest_interceptors(null_interceptor): + transport = transports.HiveMetastoreServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.HiveMetastoreServiceRestInterceptor(), + ) + client = HiveMetastoreServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.HiveMetastoreServiceRestInterceptor, "post_create_hive_database" + ) as post, + mock.patch.object( + transports.HiveMetastoreServiceRestInterceptor, + "post_create_hive_database_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.HiveMetastoreServiceRestInterceptor, "pre_create_hive_database" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = hive_metastore.CreateHiveDatabaseRequest.pb( + hive_metastore.CreateHiveDatabaseRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = hive_metastore.HiveDatabase.to_json( + hive_metastore.HiveDatabase() + ) + req.return_value.content = return_value + + request = hive_metastore.CreateHiveDatabaseRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = hive_metastore.HiveDatabase() + post_with_metadata.return_value = hive_metastore.HiveDatabase(), metadata + + client.create_hive_database( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_hive_database_rest_bad_request( + request_type=hive_metastore.GetHiveDatabaseRequest, +): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/catalogs/sample2/databases/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_hive_database(request) + + +@pytest.mark.parametrize( + "request_type", + [ + hive_metastore.GetHiveDatabaseRequest, + dict, + ], +) +def test_get_hive_database_rest_call_success(request_type): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/catalogs/sample2/databases/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = hive_metastore.HiveDatabase( + name="name_value", + description="description_value", + location_uri="location_uri_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = hive_metastore.HiveDatabase.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_hive_database(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, hive_metastore.HiveDatabase) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.location_uri == "location_uri_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_hive_database_rest_interceptors(null_interceptor): + transport = transports.HiveMetastoreServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.HiveMetastoreServiceRestInterceptor(), + ) + client = HiveMetastoreServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.HiveMetastoreServiceRestInterceptor, "post_get_hive_database" + ) as post, + mock.patch.object( + transports.HiveMetastoreServiceRestInterceptor, + "post_get_hive_database_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.HiveMetastoreServiceRestInterceptor, "pre_get_hive_database" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = hive_metastore.GetHiveDatabaseRequest.pb( + hive_metastore.GetHiveDatabaseRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = hive_metastore.HiveDatabase.to_json( + hive_metastore.HiveDatabase() + ) + req.return_value.content = return_value + + request = hive_metastore.GetHiveDatabaseRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = hive_metastore.HiveDatabase() + post_with_metadata.return_value = hive_metastore.HiveDatabase(), metadata + + client.get_hive_database( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_hive_databases_rest_bad_request( + request_type=hive_metastore.ListHiveDatabasesRequest, +): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/catalogs/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_hive_databases(request) + + +@pytest.mark.parametrize( + "request_type", + [ + hive_metastore.ListHiveDatabasesRequest, + dict, + ], +) +def test_list_hive_databases_rest_call_success(request_type): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/catalogs/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = hive_metastore.ListHiveDatabasesResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = hive_metastore.ListHiveDatabasesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_hive_databases(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListHiveDatabasesPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_hive_databases_rest_interceptors(null_interceptor): + transport = transports.HiveMetastoreServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.HiveMetastoreServiceRestInterceptor(), + ) + client = HiveMetastoreServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.HiveMetastoreServiceRestInterceptor, "post_list_hive_databases" + ) as post, + mock.patch.object( + transports.HiveMetastoreServiceRestInterceptor, + "post_list_hive_databases_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.HiveMetastoreServiceRestInterceptor, "pre_list_hive_databases" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = hive_metastore.ListHiveDatabasesRequest.pb( + hive_metastore.ListHiveDatabasesRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = hive_metastore.ListHiveDatabasesResponse.to_json( + hive_metastore.ListHiveDatabasesResponse() + ) + req.return_value.content = return_value + + request = hive_metastore.ListHiveDatabasesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = hive_metastore.ListHiveDatabasesResponse() + post_with_metadata.return_value = ( + hive_metastore.ListHiveDatabasesResponse(), + metadata, + ) + + client.list_hive_databases( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_hive_database_rest_bad_request( + request_type=hive_metastore.UpdateHiveDatabaseRequest, +): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "hive_database": {"name": "projects/sample1/catalogs/sample2/databases/sample3"} + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.update_hive_database(request) + + +@pytest.mark.parametrize( + "request_type", + [ + hive_metastore.UpdateHiveDatabaseRequest, + dict, + ], +) +def test_update_hive_database_rest_call_success(request_type): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "hive_database": {"name": "projects/sample1/catalogs/sample2/databases/sample3"} + } + request_init["hive_database"] = { + "name": "projects/sample1/catalogs/sample2/databases/sample3", + "description": "description_value", + "location_uri": "location_uri_value", + "parameters": {}, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = hive_metastore.UpdateHiveDatabaseRequest.meta.fields["hive_database"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["hive_database"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["hive_database"][field])): + del request_init["hive_database"][field][i][subfield] + else: + del request_init["hive_database"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = hive_metastore.HiveDatabase( + name="name_value", + description="description_value", + location_uri="location_uri_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = hive_metastore.HiveDatabase.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.update_hive_database(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, hive_metastore.HiveDatabase) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.location_uri == "location_uri_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_hive_database_rest_interceptors(null_interceptor): + transport = transports.HiveMetastoreServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.HiveMetastoreServiceRestInterceptor(), + ) + client = HiveMetastoreServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.HiveMetastoreServiceRestInterceptor, "post_update_hive_database" + ) as post, + mock.patch.object( + transports.HiveMetastoreServiceRestInterceptor, + "post_update_hive_database_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.HiveMetastoreServiceRestInterceptor, "pre_update_hive_database" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = hive_metastore.UpdateHiveDatabaseRequest.pb( + hive_metastore.UpdateHiveDatabaseRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = hive_metastore.HiveDatabase.to_json( + hive_metastore.HiveDatabase() + ) + req.return_value.content = return_value + + request = hive_metastore.UpdateHiveDatabaseRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = hive_metastore.HiveDatabase() + post_with_metadata.return_value = hive_metastore.HiveDatabase(), metadata + + client.update_hive_database( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_hive_database_rest_bad_request( + request_type=hive_metastore.DeleteHiveDatabaseRequest, +): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/catalogs/sample2/databases/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_hive_database(request) + + +@pytest.mark.parametrize( + "request_type", + [ + hive_metastore.DeleteHiveDatabaseRequest, + dict, + ], +) +def test_delete_hive_database_rest_call_success(request_type): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/catalogs/sample2/databases/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "" + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_hive_database(request) + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_hive_database_rest_interceptors(null_interceptor): + transport = transports.HiveMetastoreServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.HiveMetastoreServiceRestInterceptor(), + ) + client = HiveMetastoreServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.HiveMetastoreServiceRestInterceptor, "pre_delete_hive_database" + ) as pre, + ): + pre.assert_not_called() + pb_message = hive_metastore.DeleteHiveDatabaseRequest.pb( + hive_metastore.DeleteHiveDatabaseRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + request = hive_metastore.DeleteHiveDatabaseRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_hive_database( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_create_hive_table_rest_bad_request( + request_type=hive_metastore.CreateHiveTableRequest, +): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/catalogs/sample2/databases/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.create_hive_table(request) + + +@pytest.mark.parametrize( + "request_type", + [ + hive_metastore.CreateHiveTableRequest, + dict, + ], +) +def test_create_hive_table_rest_call_success(request_type): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/catalogs/sample2/databases/sample3"} + request_init["hive_table"] = { + "name": "name_value", + "description": "description_value", + "storage_descriptor": { + "columns": [ + { + "name": "name_value", + "type_": "type__value", + "comment": "comment_value", + } + ], + "location_uri": "location_uri_value", + "input_format": "input_format_value", + "output_format": "output_format_value", + "compressed": True, + "num_buckets": 1184, + "serde_info": { + "name": "name_value", + "serialization_lib": "serialization_lib_value", + "description": "description_value", + "parameters": {}, + "serializer_class": "serializer_class_value", + "deserializer_class": "deserializer_class_value", + "serde_type": 1, + }, + "bucket_cols": ["bucket_cols_value1", "bucket_cols_value2"], + "sort_cols": [{"col": "col_value", "order": 540}], + "parameters": {}, + "skewed_info": { + "skewed_col_names": [ + "skewed_col_names_value1", + "skewed_col_names_value2", + ], + "skewed_col_values": [{"values": ["values_value1", "values_value2"]}], + "skewed_key_values_locations": [ + { + "values": ["values_value1", "values_value2"], + "location": "location_value", + } + ], + }, + "stored_as_sub_dirs": True, + }, + "create_time": {"seconds": 751, "nanos": 543}, + "partition_keys": {}, + "parameters": {}, + "view_original_text": "view_original_text_value", + "view_expanded_text": "view_expanded_text_value", + "table_type": "table_type_value", + "update_time": {}, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = hive_metastore.CreateHiveTableRequest.meta.fields["hive_table"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["hive_table"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["hive_table"][field])): + del request_init["hive_table"][field][i][subfield] + else: + del request_init["hive_table"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = hive_metastore.HiveTable( + name="name_value", + description="description_value", + view_original_text="view_original_text_value", + view_expanded_text="view_expanded_text_value", + table_type="table_type_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = hive_metastore.HiveTable.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_hive_table(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, hive_metastore.HiveTable) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.view_original_text == "view_original_text_value" + assert response.view_expanded_text == "view_expanded_text_value" + assert response.table_type == "table_type_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_hive_table_rest_interceptors(null_interceptor): + transport = transports.HiveMetastoreServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.HiveMetastoreServiceRestInterceptor(), + ) + client = HiveMetastoreServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.HiveMetastoreServiceRestInterceptor, "post_create_hive_table" + ) as post, + mock.patch.object( + transports.HiveMetastoreServiceRestInterceptor, + "post_create_hive_table_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.HiveMetastoreServiceRestInterceptor, "pre_create_hive_table" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = hive_metastore.CreateHiveTableRequest.pb( + hive_metastore.CreateHiveTableRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = hive_metastore.HiveTable.to_json(hive_metastore.HiveTable()) + req.return_value.content = return_value + + request = hive_metastore.CreateHiveTableRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = hive_metastore.HiveTable() + post_with_metadata.return_value = hive_metastore.HiveTable(), metadata + + client.create_hive_table( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_hive_table_rest_bad_request( + request_type=hive_metastore.GetHiveTableRequest, +): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/catalogs/sample2/databases/sample3/tables/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_hive_table(request) + + +@pytest.mark.parametrize( + "request_type", + [ + hive_metastore.GetHiveTableRequest, + dict, + ], +) +def test_get_hive_table_rest_call_success(request_type): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/catalogs/sample2/databases/sample3/tables/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = hive_metastore.HiveTable( + name="name_value", + description="description_value", + view_original_text="view_original_text_value", + view_expanded_text="view_expanded_text_value", + table_type="table_type_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = hive_metastore.HiveTable.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_hive_table(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, hive_metastore.HiveTable) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.view_original_text == "view_original_text_value" + assert response.view_expanded_text == "view_expanded_text_value" + assert response.table_type == "table_type_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_hive_table_rest_interceptors(null_interceptor): + transport = transports.HiveMetastoreServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.HiveMetastoreServiceRestInterceptor(), + ) + client = HiveMetastoreServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.HiveMetastoreServiceRestInterceptor, "post_get_hive_table" + ) as post, + mock.patch.object( + transports.HiveMetastoreServiceRestInterceptor, + "post_get_hive_table_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.HiveMetastoreServiceRestInterceptor, "pre_get_hive_table" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = hive_metastore.GetHiveTableRequest.pb( + hive_metastore.GetHiveTableRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = hive_metastore.HiveTable.to_json(hive_metastore.HiveTable()) + req.return_value.content = return_value + + request = hive_metastore.GetHiveTableRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = hive_metastore.HiveTable() + post_with_metadata.return_value = hive_metastore.HiveTable(), metadata + + client.get_hive_table( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_hive_tables_rest_bad_request( + request_type=hive_metastore.ListHiveTablesRequest, +): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/catalogs/sample2/databases/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_hive_tables(request) + + +@pytest.mark.parametrize( + "request_type", + [ + hive_metastore.ListHiveTablesRequest, + dict, + ], +) +def test_list_hive_tables_rest_call_success(request_type): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/catalogs/sample2/databases/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = hive_metastore.ListHiveTablesResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = hive_metastore.ListHiveTablesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_hive_tables(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListHiveTablesPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_hive_tables_rest_interceptors(null_interceptor): + transport = transports.HiveMetastoreServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.HiveMetastoreServiceRestInterceptor(), + ) + client = HiveMetastoreServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.HiveMetastoreServiceRestInterceptor, "post_list_hive_tables" + ) as post, + mock.patch.object( + transports.HiveMetastoreServiceRestInterceptor, + "post_list_hive_tables_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.HiveMetastoreServiceRestInterceptor, "pre_list_hive_tables" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = hive_metastore.ListHiveTablesRequest.pb( + hive_metastore.ListHiveTablesRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = hive_metastore.ListHiveTablesResponse.to_json( + hive_metastore.ListHiveTablesResponse() + ) + req.return_value.content = return_value + + request = hive_metastore.ListHiveTablesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = hive_metastore.ListHiveTablesResponse() + post_with_metadata.return_value = ( + hive_metastore.ListHiveTablesResponse(), + metadata, + ) + + client.list_hive_tables( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_hive_table_rest_bad_request( + request_type=hive_metastore.UpdateHiveTableRequest, +): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "hive_table": { + "name": "projects/sample1/catalogs/sample2/databases/sample3/tables/sample4" + } + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.update_hive_table(request) + + +@pytest.mark.parametrize( + "request_type", + [ + hive_metastore.UpdateHiveTableRequest, + dict, + ], +) +def test_update_hive_table_rest_call_success(request_type): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "hive_table": { + "name": "projects/sample1/catalogs/sample2/databases/sample3/tables/sample4" + } + } + request_init["hive_table"] = { + "name": "projects/sample1/catalogs/sample2/databases/sample3/tables/sample4", + "description": "description_value", + "storage_descriptor": { + "columns": [ + { + "name": "name_value", + "type_": "type__value", + "comment": "comment_value", + } + ], + "location_uri": "location_uri_value", + "input_format": "input_format_value", + "output_format": "output_format_value", + "compressed": True, + "num_buckets": 1184, + "serde_info": { + "name": "name_value", + "serialization_lib": "serialization_lib_value", + "description": "description_value", + "parameters": {}, + "serializer_class": "serializer_class_value", + "deserializer_class": "deserializer_class_value", + "serde_type": 1, + }, + "bucket_cols": ["bucket_cols_value1", "bucket_cols_value2"], + "sort_cols": [{"col": "col_value", "order": 540}], + "parameters": {}, + "skewed_info": { + "skewed_col_names": [ + "skewed_col_names_value1", + "skewed_col_names_value2", + ], + "skewed_col_values": [{"values": ["values_value1", "values_value2"]}], + "skewed_key_values_locations": [ + { + "values": ["values_value1", "values_value2"], + "location": "location_value", + } + ], + }, + "stored_as_sub_dirs": True, + }, + "create_time": {"seconds": 751, "nanos": 543}, + "partition_keys": {}, + "parameters": {}, + "view_original_text": "view_original_text_value", + "view_expanded_text": "view_expanded_text_value", + "table_type": "table_type_value", + "update_time": {}, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = hive_metastore.UpdateHiveTableRequest.meta.fields["hive_table"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["hive_table"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["hive_table"][field])): + del request_init["hive_table"][field][i][subfield] + else: + del request_init["hive_table"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = hive_metastore.HiveTable( + name="name_value", + description="description_value", + view_original_text="view_original_text_value", + view_expanded_text="view_expanded_text_value", + table_type="table_type_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = hive_metastore.HiveTable.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.update_hive_table(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, hive_metastore.HiveTable) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.view_original_text == "view_original_text_value" + assert response.view_expanded_text == "view_expanded_text_value" + assert response.table_type == "table_type_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_hive_table_rest_interceptors(null_interceptor): + transport = transports.HiveMetastoreServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.HiveMetastoreServiceRestInterceptor(), + ) + client = HiveMetastoreServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.HiveMetastoreServiceRestInterceptor, "post_update_hive_table" + ) as post, + mock.patch.object( + transports.HiveMetastoreServiceRestInterceptor, + "post_update_hive_table_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.HiveMetastoreServiceRestInterceptor, "pre_update_hive_table" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = hive_metastore.UpdateHiveTableRequest.pb( + hive_metastore.UpdateHiveTableRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = hive_metastore.HiveTable.to_json(hive_metastore.HiveTable()) + req.return_value.content = return_value + + request = hive_metastore.UpdateHiveTableRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = hive_metastore.HiveTable() + post_with_metadata.return_value = hive_metastore.HiveTable(), metadata + + client.update_hive_table( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_hive_table_rest_bad_request( + request_type=hive_metastore.DeleteHiveTableRequest, +): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/catalogs/sample2/databases/sample3/tables/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_hive_table(request) + + +@pytest.mark.parametrize( + "request_type", + [ + hive_metastore.DeleteHiveTableRequest, + dict, + ], +) +def test_delete_hive_table_rest_call_success(request_type): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/catalogs/sample2/databases/sample3/tables/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "" + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_hive_table(request) + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_hive_table_rest_interceptors(null_interceptor): + transport = transports.HiveMetastoreServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.HiveMetastoreServiceRestInterceptor(), + ) + client = HiveMetastoreServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.HiveMetastoreServiceRestInterceptor, "pre_delete_hive_table" + ) as pre, + ): + pre.assert_not_called() + pb_message = hive_metastore.DeleteHiveTableRequest.pb( + hive_metastore.DeleteHiveTableRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + request = hive_metastore.DeleteHiveTableRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_hive_table( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_batch_create_partitions_rest_bad_request( + request_type=hive_metastore.BatchCreatePartitionsRequest, +): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/catalogs/sample2/databases/sample3/tables/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.batch_create_partitions(request) + + +@pytest.mark.parametrize( + "request_type", + [ + hive_metastore.BatchCreatePartitionsRequest, + dict, + ], +) +def test_batch_create_partitions_rest_call_success(request_type): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/catalogs/sample2/databases/sample3/tables/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = hive_metastore.BatchCreatePartitionsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = hive_metastore.BatchCreatePartitionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.batch_create_partitions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, hive_metastore.BatchCreatePartitionsResponse) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_batch_create_partitions_rest_interceptors(null_interceptor): + transport = transports.HiveMetastoreServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.HiveMetastoreServiceRestInterceptor(), + ) + client = HiveMetastoreServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.HiveMetastoreServiceRestInterceptor, + "post_batch_create_partitions", + ) as post, + mock.patch.object( + transports.HiveMetastoreServiceRestInterceptor, + "post_batch_create_partitions_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.HiveMetastoreServiceRestInterceptor, + "pre_batch_create_partitions", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = hive_metastore.BatchCreatePartitionsRequest.pb( + hive_metastore.BatchCreatePartitionsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = hive_metastore.BatchCreatePartitionsResponse.to_json( + hive_metastore.BatchCreatePartitionsResponse() + ) + req.return_value.content = return_value + + request = hive_metastore.BatchCreatePartitionsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = hive_metastore.BatchCreatePartitionsResponse() + post_with_metadata.return_value = ( + hive_metastore.BatchCreatePartitionsResponse(), + metadata, + ) + + client.batch_create_partitions( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_batch_delete_partitions_rest_bad_request( + request_type=hive_metastore.BatchDeletePartitionsRequest, +): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/catalogs/sample2/databases/sample3/tables/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.batch_delete_partitions(request) + + +@pytest.mark.parametrize( + "request_type", + [ + hive_metastore.BatchDeletePartitionsRequest, + dict, + ], +) +def test_batch_delete_partitions_rest_call_success(request_type): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/catalogs/sample2/databases/sample3/tables/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "" + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.batch_delete_partitions(request) + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_batch_delete_partitions_rest_interceptors(null_interceptor): + transport = transports.HiveMetastoreServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.HiveMetastoreServiceRestInterceptor(), + ) + client = HiveMetastoreServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.HiveMetastoreServiceRestInterceptor, + "pre_batch_delete_partitions", + ) as pre, + ): + pre.assert_not_called() + pb_message = hive_metastore.BatchDeletePartitionsRequest.pb( + hive_metastore.BatchDeletePartitionsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + request = hive_metastore.BatchDeletePartitionsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.batch_delete_partitions( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_batch_update_partitions_rest_bad_request( + request_type=hive_metastore.BatchUpdatePartitionsRequest, +): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/catalogs/sample2/databases/sample3/tables/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.batch_update_partitions(request) + + +@pytest.mark.parametrize( + "request_type", + [ + hive_metastore.BatchUpdatePartitionsRequest, + dict, + ], +) +def test_batch_update_partitions_rest_call_success(request_type): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/catalogs/sample2/databases/sample3/tables/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = hive_metastore.BatchUpdatePartitionsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = hive_metastore.BatchUpdatePartitionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.batch_update_partitions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, hive_metastore.BatchUpdatePartitionsResponse) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_batch_update_partitions_rest_interceptors(null_interceptor): + transport = transports.HiveMetastoreServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.HiveMetastoreServiceRestInterceptor(), + ) + client = HiveMetastoreServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.HiveMetastoreServiceRestInterceptor, + "post_batch_update_partitions", + ) as post, + mock.patch.object( + transports.HiveMetastoreServiceRestInterceptor, + "post_batch_update_partitions_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.HiveMetastoreServiceRestInterceptor, + "pre_batch_update_partitions", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = hive_metastore.BatchUpdatePartitionsRequest.pb( + hive_metastore.BatchUpdatePartitionsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = hive_metastore.BatchUpdatePartitionsResponse.to_json( + hive_metastore.BatchUpdatePartitionsResponse() + ) + req.return_value.content = return_value + + request = hive_metastore.BatchUpdatePartitionsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = hive_metastore.BatchUpdatePartitionsResponse() + post_with_metadata.return_value = ( + hive_metastore.BatchUpdatePartitionsResponse(), + metadata, + ) + + client.batch_update_partitions( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_partitions_rest_bad_request( + request_type=hive_metastore.ListPartitionsRequest, +): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/catalogs/sample2/databases/sample3/tables/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_partitions(request) + + +@pytest.mark.parametrize( + "request_type", + [ + hive_metastore.ListPartitionsRequest, + dict, + ], +) +def test_list_partitions_rest_call_success(request_type): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/catalogs/sample2/databases/sample3/tables/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = hive_metastore.ListPartitionsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = hive_metastore.ListPartitionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + json_return_value = "[{}]".format(json_return_value) + response_value.iter_content = mock.Mock(return_value=iter(json_return_value)) + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_partitions(request) + + assert isinstance(response, Iterable) + response = next(response) + + # Establish that the response is the type that we expect. + assert isinstance(response, hive_metastore.ListPartitionsResponse) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_partitions_rest_interceptors(null_interceptor): + transport = transports.HiveMetastoreServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.HiveMetastoreServiceRestInterceptor(), + ) + client = HiveMetastoreServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.HiveMetastoreServiceRestInterceptor, "post_list_partitions" + ) as post, + mock.patch.object( + transports.HiveMetastoreServiceRestInterceptor, + "post_list_partitions_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.HiveMetastoreServiceRestInterceptor, "pre_list_partitions" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = hive_metastore.ListPartitionsRequest.pb( + hive_metastore.ListPartitionsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = hive_metastore.ListPartitionsResponse.to_json( + hive_metastore.ListPartitionsResponse() + ) + req.return_value.iter_content = mock.Mock(return_value=iter(return_value)) + + request = hive_metastore.ListPartitionsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = hive_metastore.ListPartitionsResponse() + post_with_metadata.return_value = ( + hive_metastore.ListPartitionsResponse(), + metadata, + ) + + client.list_partitions( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_failover_hive_catalog_rest_bad_request( + request_type=hive_metastore.FailoverHiveCatalogRequest, +): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/catalogs/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.failover_hive_catalog(request) + + +@pytest.mark.parametrize( + "request_type", + [ + hive_metastore.FailoverHiveCatalogRequest, + dict, + ], +) +def test_failover_hive_catalog_rest_call_success(request_type): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/catalogs/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = hive_metastore.FailoverHiveCatalogResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = hive_metastore.FailoverHiveCatalogResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.failover_hive_catalog(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, hive_metastore.FailoverHiveCatalogResponse) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_failover_hive_catalog_rest_interceptors(null_interceptor): + transport = transports.HiveMetastoreServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.HiveMetastoreServiceRestInterceptor(), + ) + client = HiveMetastoreServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.HiveMetastoreServiceRestInterceptor, "post_failover_hive_catalog" + ) as post, + mock.patch.object( + transports.HiveMetastoreServiceRestInterceptor, + "post_failover_hive_catalog_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.HiveMetastoreServiceRestInterceptor, "pre_failover_hive_catalog" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = hive_metastore.FailoverHiveCatalogRequest.pb( + hive_metastore.FailoverHiveCatalogRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = hive_metastore.FailoverHiveCatalogResponse.to_json( + hive_metastore.FailoverHiveCatalogResponse() + ) + req.return_value.content = return_value + + request = hive_metastore.FailoverHiveCatalogRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = hive_metastore.FailoverHiveCatalogResponse() + post_with_metadata.return_value = ( + hive_metastore.FailoverHiveCatalogResponse(), + metadata, + ) + + client.failover_hive_catalog( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_initialize_client_w_rest(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_hive_catalog_empty_call_rest(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_hive_catalog), "__call__" + ) as call: + client.create_hive_catalog(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hive_metastore.CreateHiveCatalogRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_hive_catalog_empty_call_rest(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_hive_catalog), "__call__") as call: + client.get_hive_catalog(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hive_metastore.GetHiveCatalogRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_hive_catalogs_empty_call_rest(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_hive_catalogs), "__call__" + ) as call: + client.list_hive_catalogs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hive_metastore.ListHiveCatalogsRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_hive_catalog_empty_call_rest(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_hive_catalog), "__call__" + ) as call: + client.update_hive_catalog(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hive_metastore.UpdateHiveCatalogRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_hive_catalog_empty_call_rest(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_hive_catalog), "__call__" + ) as call: + client.delete_hive_catalog(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hive_metastore.DeleteHiveCatalogRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_hive_database_empty_call_rest(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_hive_database), "__call__" + ) as call: + client.create_hive_database(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hive_metastore.CreateHiveDatabaseRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_hive_database_empty_call_rest(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_hive_database), "__call__" + ) as call: + client.get_hive_database(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hive_metastore.GetHiveDatabaseRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_hive_databases_empty_call_rest(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_hive_databases), "__call__" + ) as call: + client.list_hive_databases(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hive_metastore.ListHiveDatabasesRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_hive_database_empty_call_rest(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_hive_database), "__call__" + ) as call: + client.update_hive_database(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hive_metastore.UpdateHiveDatabaseRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_hive_database_empty_call_rest(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_hive_database), "__call__" + ) as call: + client.delete_hive_database(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hive_metastore.DeleteHiveDatabaseRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_hive_table_empty_call_rest(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_hive_table), "__call__" + ) as call: + client.create_hive_table(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hive_metastore.CreateHiveTableRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_hive_table_empty_call_rest(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_hive_table), "__call__") as call: + client.get_hive_table(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hive_metastore.GetHiveTableRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_hive_tables_empty_call_rest(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_hive_tables), "__call__") as call: + client.list_hive_tables(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hive_metastore.ListHiveTablesRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_hive_table_empty_call_rest(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_hive_table), "__call__" + ) as call: + client.update_hive_table(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hive_metastore.UpdateHiveTableRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_hive_table_empty_call_rest(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_hive_table), "__call__" + ) as call: + client.delete_hive_table(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hive_metastore.DeleteHiveTableRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_batch_create_partitions_empty_call_rest(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.batch_create_partitions), "__call__" + ) as call: + client.batch_create_partitions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hive_metastore.BatchCreatePartitionsRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_batch_delete_partitions_empty_call_rest(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.batch_delete_partitions), "__call__" + ) as call: + client.batch_delete_partitions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hive_metastore.BatchDeletePartitionsRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_batch_update_partitions_empty_call_rest(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.batch_update_partitions), "__call__" + ) as call: + client.batch_update_partitions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hive_metastore.BatchUpdatePartitionsRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_partitions_empty_call_rest(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_partitions), "__call__") as call: + client.list_partitions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hive_metastore.ListPartitionsRequest() + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_failover_hive_catalog_empty_call_rest(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.failover_hive_catalog), "__call__" + ) as call: + client.failover_hive_catalog(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = hive_metastore.FailoverHiveCatalogRequest() + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.HiveMetastoreServiceGrpcTransport, + ) + + +def test_hive_metastore_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.HiveMetastoreServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_hive_metastore_service_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.biglake_hive_v1.services.hive_metastore_service.transports.HiveMetastoreServiceTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.HiveMetastoreServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "create_hive_catalog", + "get_hive_catalog", + "list_hive_catalogs", + "update_hive_catalog", + "delete_hive_catalog", + "create_hive_database", + "get_hive_database", + "list_hive_databases", + "update_hive_database", + "delete_hive_database", + "create_hive_table", + "get_hive_table", + "list_hive_tables", + "update_hive_table", + "delete_hive_table", + "batch_create_partitions", + "batch_delete_partitions", + "batch_update_partitions", + "list_partitions", + "failover_hive_catalog", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_hive_metastore_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with ( + mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, + mock.patch( + "google.cloud.biglake_hive_v1.services.hive_metastore_service.transports.HiveMetastoreServiceTransport._prep_wrapped_messages" + ) as Transport, + ): + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.HiveMetastoreServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/bigquery", + "https://www.googleapis.com/auth/cloud-platform", + ), + quota_project_id="octopus", + ) + + +def test_hive_metastore_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with ( + mock.patch.object(google.auth, "default", autospec=True) as adc, + mock.patch( + "google.cloud.biglake_hive_v1.services.hive_metastore_service.transports.HiveMetastoreServiceTransport._prep_wrapped_messages" + ) as Transport, + ): + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.HiveMetastoreServiceTransport() + adc.assert_called_once() + + +def test_hive_metastore_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + HiveMetastoreServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/bigquery", + "https://www.googleapis.com/auth/cloud-platform", + ), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.HiveMetastoreServiceGrpcTransport, + transports.HiveMetastoreServiceGrpcAsyncIOTransport, + ], +) +def test_hive_metastore_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/bigquery", + "https://www.googleapis.com/auth/cloud-platform", + ), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.HiveMetastoreServiceGrpcTransport, + transports.HiveMetastoreServiceGrpcAsyncIOTransport, + transports.HiveMetastoreServiceRestTransport, + ], +) +def test_hive_metastore_service_transport_auth_gdch_credentials(transport_class): + host = "https://language.com" + api_audience_tests = [None, "https://language2.com"] + api_audience_expect = [host, "https://language2.com"] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, "default", autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock( + return_value=gdch_mock + ) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with(e) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.HiveMetastoreServiceGrpcTransport, grpc_helpers), + (transports.HiveMetastoreServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +def test_hive_metastore_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with ( + mock.patch.object(google.auth, "default", autospec=True) as adc, + mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel, + ): + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "biglake.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + "https://www.googleapis.com/auth/bigquery", + "https://www.googleapis.com/auth/cloud-platform", + ), + scopes=["1", "2"], + default_host="biglake.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.HiveMetastoreServiceGrpcTransport, + transports.HiveMetastoreServiceGrpcAsyncIOTransport, + ], +) +def test_hive_metastore_service_grpc_transport_client_cert_source_for_mtls( + transport_class, +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds, + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback, + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, private_key=expected_key + ) + + +def test_hive_metastore_service_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ) as mock_configure_mtls_channel: + transports.HiveMetastoreServiceRestTransport( + credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_hive_metastore_service_host_no_port(transport_name): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="biglake.googleapis.com" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "biglake.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://biglake.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_hive_metastore_service_host_with_port(transport_name): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="biglake.googleapis.com:8000" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "biglake.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://biglake.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_hive_metastore_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = HiveMetastoreServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = HiveMetastoreServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.create_hive_catalog._session + session2 = client2.transport.create_hive_catalog._session + assert session1 != session2 + session1 = client1.transport.get_hive_catalog._session + session2 = client2.transport.get_hive_catalog._session + assert session1 != session2 + session1 = client1.transport.list_hive_catalogs._session + session2 = client2.transport.list_hive_catalogs._session + assert session1 != session2 + session1 = client1.transport.update_hive_catalog._session + session2 = client2.transport.update_hive_catalog._session + assert session1 != session2 + session1 = client1.transport.delete_hive_catalog._session + session2 = client2.transport.delete_hive_catalog._session + assert session1 != session2 + session1 = client1.transport.create_hive_database._session + session2 = client2.transport.create_hive_database._session + assert session1 != session2 + session1 = client1.transport.get_hive_database._session + session2 = client2.transport.get_hive_database._session + assert session1 != session2 + session1 = client1.transport.list_hive_databases._session + session2 = client2.transport.list_hive_databases._session + assert session1 != session2 + session1 = client1.transport.update_hive_database._session + session2 = client2.transport.update_hive_database._session + assert session1 != session2 + session1 = client1.transport.delete_hive_database._session + session2 = client2.transport.delete_hive_database._session + assert session1 != session2 + session1 = client1.transport.create_hive_table._session + session2 = client2.transport.create_hive_table._session + assert session1 != session2 + session1 = client1.transport.get_hive_table._session + session2 = client2.transport.get_hive_table._session + assert session1 != session2 + session1 = client1.transport.list_hive_tables._session + session2 = client2.transport.list_hive_tables._session + assert session1 != session2 + session1 = client1.transport.update_hive_table._session + session2 = client2.transport.update_hive_table._session + assert session1 != session2 + session1 = client1.transport.delete_hive_table._session + session2 = client2.transport.delete_hive_table._session + assert session1 != session2 + session1 = client1.transport.batch_create_partitions._session + session2 = client2.transport.batch_create_partitions._session + assert session1 != session2 + session1 = client1.transport.batch_delete_partitions._session + session2 = client2.transport.batch_delete_partitions._session + assert session1 != session2 + session1 = client1.transport.batch_update_partitions._session + session2 = client2.transport.batch_update_partitions._session + assert session1 != session2 + session1 = client1.transport.list_partitions._session + session2 = client2.transport.list_partitions._session + assert session1 != session2 + session1 = client1.transport.failover_hive_catalog._session + session2 = client2.transport.failover_hive_catalog._session + assert session1 != session2 + + +def test_hive_metastore_service_grpc_transport_channel(): + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.HiveMetastoreServiceGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_hive_metastore_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.HiveMetastoreServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.filterwarnings("ignore::FutureWarning") +@pytest.mark.parametrize( + "transport_class", + [ + transports.HiveMetastoreServiceGrpcTransport, + transports.HiveMetastoreServiceGrpcAsyncIOTransport, + ], +) +def test_hive_metastore_service_transport_channel_mtls_with_client_cert_source( + transport_class, +): + with mock.patch( + "grpc.ssl_channel_credentials", autospec=True + ) as grpc_ssl_channel_cred: + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize( + "transport_class", + [ + transports.HiveMetastoreServiceGrpcTransport, + transports.HiveMetastoreServiceGrpcAsyncIOTransport, + ], +) +def test_hive_metastore_service_transport_channel_mtls_with_adc(transport_class): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_catalog_path(): + project = "squid" + catalog = "clam" + expected = "projects/{project}/catalogs/{catalog}".format( + project=project, + catalog=catalog, + ) + actual = HiveMetastoreServiceClient.catalog_path(project, catalog) + assert expected == actual + + +def test_parse_catalog_path(): + expected = { + "project": "whelk", + "catalog": "octopus", + } + path = HiveMetastoreServiceClient.catalog_path(**expected) + + # Check that the path construction is reversible. + actual = HiveMetastoreServiceClient.parse_catalog_path(path) + assert expected == actual + + +def test_namespace_path(): + project = "oyster" + catalog = "nudibranch" + database = "cuttlefish" + expected = "projects/{project}/catalogs/{catalog}/databases/{database}".format( + project=project, + catalog=catalog, + database=database, + ) + actual = HiveMetastoreServiceClient.namespace_path(project, catalog, database) + assert expected == actual + + +def test_parse_namespace_path(): + expected = { + "project": "mussel", + "catalog": "winkle", + "database": "nautilus", + } + path = HiveMetastoreServiceClient.namespace_path(**expected) + + # Check that the path construction is reversible. + actual = HiveMetastoreServiceClient.parse_namespace_path(path) + assert expected == actual + + +def test_table_path(): + project = "scallop" + catalog = "abalone" + database = "squid" + table = "clam" + expected = "projects/{project}/catalogs/{catalog}/databases/{database}/tables/{table}".format( + project=project, + catalog=catalog, + database=database, + table=table, + ) + actual = HiveMetastoreServiceClient.table_path(project, catalog, database, table) + assert expected == actual + + +def test_parse_table_path(): + expected = { + "project": "whelk", + "catalog": "octopus", + "database": "oyster", + "table": "nudibranch", + } + path = HiveMetastoreServiceClient.table_path(**expected) + + # Check that the path construction is reversible. + actual = HiveMetastoreServiceClient.parse_table_path(path) + assert expected == actual + + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = HiveMetastoreServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = HiveMetastoreServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = HiveMetastoreServiceClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = HiveMetastoreServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = HiveMetastoreServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = HiveMetastoreServiceClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = HiveMetastoreServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = HiveMetastoreServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = HiveMetastoreServiceClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format( + project=project, + ) + actual = HiveMetastoreServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = HiveMetastoreServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = HiveMetastoreServiceClient.parse_common_project_path(path) + assert expected == actual + + +def test_common_location_path(): + project = "whelk" + location = "octopus" + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + actual = HiveMetastoreServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = HiveMetastoreServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = HiveMetastoreServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object( + transports.HiveMetastoreServiceTransport, "_prep_wrapped_messages" + ) as prep: + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.HiveMetastoreServiceTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = HiveMetastoreServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +def test_transport_close_grpc(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = HiveMetastoreServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +def test_client_ctx(): + transports = [ + "rest", + "grpc", + ] + for transport in transports: + client = HiveMetastoreServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + + +@pytest.mark.parametrize( + "client_class,transport_class", + [ + (HiveMetastoreServiceClient, transports.HiveMetastoreServiceGrpcTransport), + ( + HiveMetastoreServiceAsyncClient, + transports.HiveMetastoreServiceGrpcAsyncIOTransport, + ), + ], +) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/release-please-individual-config.json b/release-please-individual-config.json index d218ce1f5f3b..eafa3ccd448d 100644 --- a/release-please-individual-config.json +++ b/release-please-individual-config.json @@ -2,14 +2,20 @@ "bump-minor-pre-major": true, "bump-patch-for-minor-pre-major": true, "packages": { - "packages/google-cloud-workloadidentity": { - "component": "google-cloud-workloadidentity", + "packages/google-cloud-biglake-hive": { + "component": "google-cloud-biglake-hive", "extra-files": [ - "google/cloud/workloadidentity/gapic_version.py", - "google/cloud/workloadidentity_v1/gapic_version.py", + "google/cloud/biglake/hive/gapic_version.py", + "google/cloud/biglake/hive_v1/gapic_version.py", + "google/cloud/biglake/hive_v1beta/gapic_version.py", { "jsonpath": "$.clientLibrary.version", - "path": "samples/generated_samples/snippet_metadata_google.cloud.workloadidentity.v1.json", + "path": "samples/generated_samples/snippet_metadata_google.cloud.biglake.hive.v1.json", + "type": "json" + }, + { + "jsonpath": "$.clientLibrary.version", + "path": "samples/generated_samples/snippet_metadata_google.cloud.biglake.hive.v1beta.json", "type": "json" } ] @@ -26,6 +32,18 @@ } ] }, + "packages/google-cloud-workloadidentity": { + "component": "google-cloud-workloadidentity", + "extra-files": [ + "google/cloud/workloadidentity/gapic_version.py", + "google/cloud/workloadidentity_v1/gapic_version.py", + { + "jsonpath": "$.clientLibrary.version", + "path": "samples/generated_samples/snippet_metadata_google.cloud.workloadidentity.v1.json", + "type": "json" + } + ] + }, "packages/google-crc32c": { "component": "google-crc32c" }, @@ -43,4 +61,4 @@ }, "release-type": "python-librarian", "separate-pull-requests": true -} +} \ No newline at end of file